简体   繁体   English

Python 表达式求值顺序

[英]Python expression evaluation order

I don't see why the following expression evaluates to False :我不明白为什么以下表达式的计算结果为False

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

in and == has the same precedence and groups left to right, but: in==具有相同的优先级和从左到右的组,但是:

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

and

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

Where is the problem with the parenthesis?括号的问题在哪里?

Comparison operators at the same level "chain".同级“链”上的比较运算符。 You may have seen something such as 10 < x < 25 , which expands to (10 < x) and (x < 25) .您可能已经看到诸如10 < x < 25之类的东西,它扩展为(10 < x) and (x < 25)

Similarly, your original expression expands to同样,您的原始表达式扩展为

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

The first expression evaluates as True , as you already know.如您所知,第一个表达式的计算结果为True The second expression returns False , giving the result you see.第二个表达式返回False ,给出您看到的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM