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

2024-05-13 15:23:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

顺便说一句,这本书没有解释。


Tags: false示例核心编程作者书籍元组equals
3条回答

比较元组

Python中的比较运算符可以处理元组。比较从每个元组的第一个元素开始。如果它们不与=<>进行比较,则它继续到第二个元素,依此类推。

让我们用一个例子来研究这个问题:

    #case 1
    a=(5,6)
    b=(1,4)
    if (a>b):print("a is bigger")
    else: print("b is bigger")

    #case 2
    a=(5,6)
    b=(5,4)
    if (a>b):print("a is bigger")
    else: print ("b is bigger")

    #case 3
    a=(5,6)
    b=(6,4)
    if (a>b):print("a is bigger")
    else: print("b is bigger")

案例1:

比较从每个元组的第一个元素开始。在本例中为5>;1,因此输出a更大

案例2:

比较从每个元组的第一个元素开始。在这种情况下,5>;5是不确定的。所以它进入下一个元素。6>;4,因此输出a更大

案例3:

比较从每个元组的第一个元素开始。在这种情况下,5>;6为假。所以它进入else循环打印“b更大”

结论:

元组总是比较它的第一个索引并根据程序给出输出。它不比较所有元素。

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

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://stackoverflow.com/questions/36911617/python-2-tuple-comparison:只有当第一个元组中的任何元素大于第二个元组中的相应元素时,才不要认为元组比另一个元组“大”。

Python documentation解释的。

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.

相关问题 更多 >