python - 使用大于或小于运算符比较两个列表

标签 python list

我注意到最近有一段代码直接比较了两个整数列表,如下所示:

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/

相关文章:

Python列表转置和填充

python - 分解 HTML 以链接文本和目标

读取文件时Python编码问题

python - 在 python 中合并列表

python - 尝试在 Python 中扩展列表时出现类型错误

java - 设置列表的第一个元素

python - 您可以将 "stream"图像发送到 ffmpeg 以构建视频,而不是将它们保存到磁盘吗?

python - 如果字符串具有 "\r"即回车符,则 Python 中的 json.loads(jsonstring) 会失败

python - numpy计算自定义矩阵乘法

list - Scala 整数列表列表