0是0 == 0(#evaluates为True?)

时间:2016-07-29 07:51:35

标签: python python-3.x

这令我感到困惑。即使不知道优先顺序,也可以检查收集表达式的两种可能方法是False

>>> (0 is 0) == 0
False
>>> 0 is (0 == 0)
False

但是

>>> 0 is 0 == 0
True

怎么回事?

2 个答案:

答案 0 :(得分:19)

您正在使用比较运算符链接。该表达式被解释为:

str(graph_lock_andEdges_Array)
List of 3
 $ : int [1:2, 1:2] 1 2 3 4
 $ :List of 1
  ..$ : int [1:2, 1:2] 5 6 7 8
 $ :List of 1
  ..$ : int [1:2, 1:2] 9 10 11 12
graph_lock_andEdges_Array <- NULL
str(graph_lock_andEdges_Array)
 NULL

来自Comparisons documentation

  

比较可以任意链接,例如,(0 is 0) and (0 == 0) 等同于x < y <= z,但x < y and y <= z仅评估一次(但在两种情况下y都未评估所有z被发现为假的时候。

x < y是正确的,因为Python interns small integers是一个实施细节,因此您0 is 0生成(True) and (True)

答案 1 :(得分:5)

在Python中链接比较运算符时,运算符实际上并不应用于其他运算符的结果,而是单独应用于操作数。那是x ? y ?? z(其中???应该代表某些比较运算符)既不等同于(x ? y) ?? z也不等同x ? (y ?? z),而是{{} 1}}。

这对x ? y and y ?? z和co。特别有用,允许你编写像>这样的东西并让它做你想做的事情,而不是将布尔值与数字进行比较(大多数其他情况都会发生这种情况)语言)。