为什么布尔表达式“1 in (1, 2, 3) == True”为假?

Why is the boolean expression "1 in (1, 2, 3) == True" False?

为什么1 in (1, 2, 3) == TruereturnFalse在Python中? Python 中的运算符优先级不明确吗?

因为,根据 the documentation 运算符优先级:

Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.

比较部分显示了一个链接示例:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z

所以:

1 in (1, 2, 3) == True

解释为:

(1 in (1, 2, 3)) and ((1, 2, 3) == True)

如果您通过添加括号来覆盖此链接,您将获得预期的行为:

>>> (1 in (1, 2, 3)) == True
True

请注意,与其将真实性与 TrueFalse 进行相等比较,不如使用例如if thing:if not thing:.