使用大于或小于运算符比较两个列表 [英] Comparing two lists using the greater than or less than operator

查看:97
本文介绍了使用大于或小于运算符比较两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I noticed a piece of code recently directly comparing two lists of integers like so:

a = [10,3,5, ...]
b = [5,4,3, ...,]
if a > b:
     ...

似乎有点奇怪,但我想如果list_a的所有元素都大于list_b的元素,则返回True;如果每个元素相等或list_b的元素是False,则返回False大于list_a的.因此,我对其进行了测试:

which seemed a bit peculiar, but I imagined it would return True if all of list_a's elements are larger then list_b's and False if each element is equal or list_b's elements are larger then list_a's. So I tested it:

>>> 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

但是当它变得更加模糊时:

but when it gets more fuzzy:

>>> 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实际在做什么?看来它返回的结果偏向于第一个列表,其中最左边的元素大于相应的元素?

the results are a bit stranger. What is python actually doing? It seems that it's returning the result in favour of the first list in which the left most element is greater then the corresponding?

推荐答案

来自比较序列和其他类型在Python教程中:

From Comparing Sequences and Other Types in the Python tutorial:

比较使用字典顺序:首先比较前两个项目,如果它们不同,则确定比较的结果;如果它们相等,则比较下两个项目,依此类推,直到用尽任何一个序列.

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.

另请参阅有关词典顺序的Wikipedia文章.

See also the Wikipedia article about lexicographical order.

这篇关于使用大于或小于运算符比较两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆