Python 表达式求值顺序

问题描述

我不明白为什么以下表达式的计算结果为 False

>>> 1 in [1,2,3] == True
False

in== 具有相同的优先级和从左到右的分组,但是:

>>> (1 in [1,3]) == True
True

>>> 1 in ([1,3] == True)
Traceback (most recent call last):
  File "<stdin>",line 1,in <module>
TypeError: argument of type 'bool' is not iterable

括号的问题在哪里?

解决方法

同级“链”的比较运算符。您可能已经看到诸如 10 < x < 25 之类的内容,它扩展为 (10 < x) and (x < 25)

同样,你的原始表达式扩展为

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

如您所知,第一个表达式的计算结果为 True。第二个表达式返回 False,给出您看到的结果。