Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

python - Comparing two lists using the greater than or less than operator

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

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

Ok that works. As does:

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

or:

>>> a=[1,3,1,1]
>>> b=[1,1,3,3]
>>> a>b
True
>>> b>a
False

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

See also the Wikipedia article about lexicographical order.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...