gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:29:27 36 4
gpt4 key购买 nike

我一直在看Core Python编程书,作者举了一个例子:

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

所以,我想知道,它如何/为什么等于 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://stackoverflow.com/questions/36911617/python-2-tuple-comparison : 不要认为一个元组只有当第一个元素的任何元素大于第二个中的对应元素时才“大于”另一个。

关于python - 元组比较在 Python 中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5292303/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com