问题
What is the associativity of comparison operators in Python? It is straightforward for three comparisons, but for more than that, I'm not sure how it does it. They don't seem to be right- or left-associative.
For example:
>>> 7410 >= 8690 <= -4538 < 9319 > -7092
False
>>> (((7410 >= 8690) <= -4538) < 9319) > -7092
True
So, not left-associative.
>>> 81037572 > -2025 < -4722 < 6493
False
>>> (81037572 > (-2025 < (-4722 < 6493)))
True
So it's not right-associative either.
I have seen some places that they are 'chained', but how does that work with four or more comparisons?
回答1:
Chained comparisons are expanded with and
, so:
a <= b <= c
becomes:
a <= b and b <= c
(b
is only evaluated once, though). This is explained in the language reference on comparisons.
Note that lazy evaluation means that if a > b
, the result is False
and b
is never compared to c
.
Your versions with parentheses are completely different; a <= (b <= c)
will evaluate b <= c
then compare a
to the result of that, and
isn't involved at all, so it's not meaningful to compare the results to determine associativity.
回答2:
python short-circits boolean tests from left to right:
7410>=8690<=-4538<9319>-7092 -> False
7410>=8690
is False
. that's it. the rest of the tests is not preformed.
note that
True == 1
False == 0
are both True
and apply when you compare the booleans with integers. so when you surround the statement with brackets you force python to do all the tests; in detail:
(((7410>=8690)<=-4538)<9319)>-7092
False <=-4538
False <9319
True >-7092
True
回答3:
You are making an error with types, when you write 81037572>-2025
then the system thinks of this as True
or False
and associates it with 1
and 0
. It therefore then gives you a comparison with those binary numbers.
来源:https://stackoverflow.com/questions/32536217/associativity-of-comparison-operators-in-python