在Python中,元组比较是如何工作的?

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

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

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

顺便说一下,书中没有解释.

解决方法:

元组逐位比较:
将第一个元组的第一项与第二元组的第一项进行比较;如果它们不相等(即第一个大于或小于第二个)那么这就是比较的结果,否则考虑第二个项目,然后是第三个项目,依此类推.

Common Sequence Operations

Sequences of the same type 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.

还有Value Comparisons了解更多详情:

Lexicographical comparison between built-in collections works as follows:

  • For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).
  • Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

如果不相等,则序列的排序与它们的第一个不同元素相同.例如,cmp([1,2,x],[1,2,y])返回与cmp(x,y)相同的值.如果相应的元素不存在,则较短的序列被认为较小(例如,[1,2]< [1,2,3]返回True). 注1:<和>并不是指“小于”和“大于”,而是“在之前”和“在之后”:所以(0,1)“在”之前“(1,0).

注2:元组不能被视为n维空间中的向量,根据它们的长度进行比较.

注3:参考问题https://*.com/questions/36911617/python-2-tuple-comparison:只有当第一个元素中的任何元素大于第二个元素中的相应元素时,才认为元组比另一元素“更大”.

上一篇:python – x,= … – 这个尾随逗号是逗号运算符吗?


下一篇:python – 对元组列表的列表进行排序