简体   繁体   English

python如何评估呢?

[英]How does python evaluate this?

Can someone explain how these results are possible (python 2.6): 有人可以解释一下这些结果是如何可能的(python 2.6):

>>> 1<3>2
True
>>> (1<3)>2
False
>>> 1<(3>2)
False

I would think that one of the last two would match the first one, but apparently the operators in the first statement is somehow linked?! 我认为后两个中的一个会与第一个相匹配,但是显然第一条语句中的运算符以某种方式链接了?

Your first example shows comparison chaining . 您的第一个示例显示比较链 1<3>2 means 1<3 and 3>2 (except each expression is evaluated only once). 1<3>2表示1<3 and 3>2 (每个表达式只计算一次)。 This applies to all comparison operators in Python. 这适用于Python中的所有比较运算符。

Your second two examples force one comparison to be evaluated first, resulting in a boolean value which is then compared with the remaining integer. 您的后两个示例将强制首先比较一个值,得出一个布尔值,然后将其与剩余的整数进行比较。

In your first case 1<3>2 1 is actually lesser than 3 and 3 is greater than 2 , so True . 在第一种情况下1<3>2 1实际上小于33大于2 ,因此为True

In your second case (1<3)>2 (1<3) evaluates as True that represented as 1 , so 1 is not greater than 2 . 在第二种情况下(1<3)>2 (1<3)计算结果为True ,表示为1 ,因此1不大于2

In your third case 1<(3>2) , 1 is not lesser than True that represented as 1 . 在您的第三种情况1<(3>2)1不小于表示为1 True

The last two statements compare booleans against an integer: 最后两个语句将布尔值与整数进行比较:

>>> True > 2
False
>>> 1 < True
False

The first statement is comparison chaining , which works for all boolean comparisons in Python. 第一条语句是比较链接 ,它适用于Python中的所有布尔比较。 Note from the documentation: 从文档中注意:

Comparisons yield boolean values: True or False. 比较会产生布尔值:True或False。

By placing parts of your expression in brackets, those parts get evaluated first and you end up with comparing integers and booleans. 通过将表达式的各个部分放在方括号中,这些部分将首先被求值,最后您将比较整数和布尔值。

As per docs , 根据文档

Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. 与C不同,Python中的所有比较运算都具有相同的优先级,该优先级低于任何算术,移位或按位运算。 Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics: 同样与C不同,像<b <c这样的表达式具有数学上的常规解释:

comparison ::= or_expr ( comp_operator or_expr )* 比较:: = or_expr(comp_operator or_expr)*

comp_operator ::= "<" | comp_operator :: =“ <” | ">" | “>” | "==" | “ ==” | ">=" | “> =” | "<=" | “ <=” | "<>" | “ <>” | "!=" | “!=” | "is" ["not"] | “是” [“不是”] | ["not"] "in" [“不是”]“中”

Comparisons yield boolean values: True or False . 比较会产生布尔值: TrueFalse

Comparisons can be chained arbitrarily, eg, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false). 比较可以任意链接,例如,x <y <= z等效于x <y和y <= z,除了y仅被评估一次(但是在两种情况下,当x <y被发现时,z都不被评估。是假的)。

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

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