为什么 (1 == 2 != 3) 在 Python 中求值为 False?

Why does (1 == 2 != 3) evaluate to False in Python?

为什么 (1 == 2 != 3) 在 Python 中的计算结果为 False,而 ((1 == 2) != 3)(1 == (2 != 3)) 的计算结果均为 True

这里使用什么运算符优先级?

这是由于运算符 chaining phenomenon。 Pydoc 将其解释为:

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).

如果您查看 ==!= 运算符的 precedence,您会发现它们具有 相同的优先级 因此适用于链接现象

所以基本上会发生什么:

>>>  1==2
=> False
>>> 2!=3
=> True

>>> (1==2) and (2!=3)
  # False and True
=> False

A op B op C 这样的链式表达式,其中 op 是比较运算符,与 C 的计算结果相反 (https://docs.python.org/2.3/ref/comparisons.html):

A op B and B op C

因此,您的示例被评估为

1 == 2 and 2 != 3

结果为 False