我注意到最近有一段代码直接比较了两个整数列表,如下所示:
a = [10,3,5, ...]
b = [5,4,3, ...,]
if a > b:
...
这似乎有点奇怪,但我想如果 list_a
的所有元素都大于 list_b
的元素,它会返回 True
如果每个元素相等或 list_b
的元素大于 list_a
的元素,则为 False。所以我测试了它:
>>> a=[3,3,3,3]
>>> b=[4,4,4,4]
>>> a>b
False
>>> b>a
True
好的,这行得通。就像这样:
>>> b = [1,1,1,1]
>>> a = [1,1,1,1]
>>> a>b
False
>>> b>a
False
但是当它变得更加模糊时:
>>> a=[1,1,3,1]
>>> b=[1,3,1,1]
>>> a>b
False
>>> b>a
True
或:
>>> a=[1,3,1,1]
>>> b=[1,1,3,3]
>>> a>b
True
>>> b>a
False
结果有点奇怪。 python实际上在做什么?似乎它返回的结果有利于第一个列表,其中最左边的元素大于对应的?
最佳答案
来自 Comparing Sequences and Other Types在 Python 教程中:
The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
另见关于 lexicographical order 的维基百科文章.
关于python - 使用大于或小于运算符比较两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13052857/