从1<2<3的语法糖说起

python有一个很有意思的语法糖你可以直接写1<2<3。

这复合我们通常意义上的数学不等式,但对学过C等语言其实是有疑惑的。

我们知道不等式返回的其实是个Bool值,在C中是1,0因此C中下面情况是正确的

0<0<1

因此我们看下面这个情况

True == True == False
#False
False == False == True
#False

从通常意义来说==号从右往左结合,无论如何值都应该是True,但是结果确是False

这就是源于python的一个语法糖,对于运算优先级的规定。

所有比较类型的运算符拥有同样的优先级,会从左至右链接起来共同作为一个比较段( all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section)。

in, not in, is, is not, <, <=, >, >=, !=, ==

比如一个典型的True == True == False它实质是如下的逻辑关系

(True == True) and (True == False)

文档中说明a op1 b op2 c ... y opN z实质相当于a op1 b and b op2 c and ... y opN z

所以虽然-2<-1<0符合我们正常数学上的逻辑,但这只是一个特例,正如评论中指出的1<5>3依然返回True
正是因为它符合1<5 and 5>3

参考
python operation priority

原文地址:https://www.cnblogs.com/lynsyklate/p/7989308.html