简体   繁体   English

Python中比较运算符的关联性

[英]Associativity of comparison operators in Python

What is the associativity of comparison operators in Python? 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? 我已经看到了一些“链接”的地方,但是在进行四个或更多比较时如何工作?

Chained comparisons are expanded with and , so: 链式比较使用and扩展,因此:

a <= b <= c

becomes: 变为:

a <= b and b <= c

( b is only evaluated once, though) . (不过, b仅被评估一次) 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 . 请注意,惰性评估意味着如果a > b ,则结果为False并且b永远不会与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. a <= (b <= c)将求值b <= c然后将a与该结果进行比较, and完全不涉及,因此比较结果以确定关联性是没有意义的。

python short-circits boolean tests from left to right: python short-circits布尔测试,从左到右:

7410>=8690<=-4538<9319>-7092        -> False

7410>=8690 is False . 7410>=8690False 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. 都是True并且在将布尔值与整数进行比较时适用。 so when you surround the statement with brackets you force python to do all the tests; 因此,当用括号将语句括起来时,将强制python执行所有测试; in detail: 详细:

(((7410>=8690)<=-4538)<9319)>-7092
      False   <=-4538
            False     <9319
                    True  >-7092
                         True

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 . 您在编写类型时出错,当您编写81037572>-2025 ,系统会将其视为TrueFalse并将其与10关联。 It therefore then gives you a comparison with those binary numbers. 因此,它然后为您提供了与那些二进制数的比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM