Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 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 from:https://stackoverflow.com/questions/13052857/comparing-two-lists-using-the-greater-than-or-less-than-operator

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...