Associativity of comparison operators in Python

孤人 提交于 2019-12-11 13:00:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!