python元组比较 [英] python tuple comparison

查看:457
本文介绍了python元组比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读核心Python编程书,作者展示了一个例子:

 (4,5) ; (3,5)#等于假

所以我想知道,为什么它等于假? python如何比较这两个元组?



Btw,这本书没有解释。

解决方案

元组按位置进行比较:
第一个元组的第一个项目与第二个元组的第一个项目比较;如果它们不相等,则这是比较的结果,否则考虑第二项,然后考虑第三项,等等。



参见 doc


序列类型也支持比较。特别地,元组和列表通过比较对应元素来按字典顺序进行比较。这意味着为了比较相等,每个元素必须比较相等,两个序列必须是相同的类型和具有相同的长度。


另外


元组和列表使用相应元素的比较按字典顺序进行比较。这意味着为了比较相等,每个元素必须比较相等,两个序列必须是相同的类型和具有相同的长度。


如果不相等,则序列与它们的第一不同元素相同地排序。例如,cmp([1,2,x],[1,2,y])返回与cmp(x,y)相同的值。如果相应的元素不存在,较短的序列被认为较小(例如,[1,2] <[1,2,3]返回True)。



注意< > 大于但在...之前和在之后:so(0,1)在(1,0)之前。



: : :引用问题 Python 2元组比较:不要认为元组是大于另一个只有第一个的任何元素大于第二个


中的相应元素

I have been reading the Core Python programming book and the author shows an example like:

(4,5) < (3,5) # Equals false

So I'm wondering, how/why does it equal false? How does python compare these two tuples?

Btw, it's not explained in the book.

解决方案

Tuples are compared position by position: the first item of first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.

See doc:

Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

Also this:

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).

Note that < and > do not mean "smaller then" and "greater then" but "is before" and "is after": so (0, 1) "is before" (1, 0).

Note 2: tuples must not be considered as coordinates in a n-dimensional space!

Note 3: referring to question Python 2 tuple comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second

这篇关于python元组比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆