300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python中元组可以比较大小吗_python元组比较

python中元组可以比较大小吗_python元组比较

时间:2019-08-10 13:57:33

相关推荐

python中元组可以比较大小吗_python元组比较

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。