python 运算符优先级如何与双重比较一起使用?
How does python operator precedence work with double comparisons?
-3<-2<-1
returns True
.
但是我希望它被解释为
(-3<-2)<-1
True<-1
1<-1
False
这怎么可能?
Unlike C, expressions like a < b < c
have the interpretation that is conventional in mathematics
Comparisons can be chained arbitrarily, e.g., 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
).
因此
-3 < -2 < -1
等同于
-3 < -2 and -2 < -1 # where -2 is evaluated only once
在documentation中声明它是语言的一部分
这是一个chained comparison。它不是像 (-3 < -2) < -1
这样的左结合或像 -3 < (-2 < -1)
这样的右结合,而是实际上被视为
(-3 < -2) and (-2 < -1)
除了 -2
最多计算一次。
-3<-2<-1
returns True
.
但是我希望它被解释为
(-3<-2)<-1
True<-1
1<-1
False
这怎么可能?
Unlike C, expressions like
a < b < c
have the interpretation that is conventional in mathematicsComparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to befalse
).
因此
-3 < -2 < -1
等同于
-3 < -2 and -2 < -1 # where -2 is evaluated only once
在documentation中声明它是语言的一部分
这是一个chained comparison。它不是像 (-3 < -2) < -1
这样的左结合或像 -3 < (-2 < -1)
这样的右结合,而是实际上被视为
(-3 < -2) and (-2 < -1)
除了 -2
最多计算一次。