简体   繁体   English

为什么 (1 in [1,0] == True) 评估为 False?

[英]Why does (1 in [1,0] == True) evaluate to False?

When I was looking at answers to this question , I found I didn't understand my own answer.当我查看这个问题的答案时,我发现我不明白自己的答案。

I don't really understand how this is being parsed.我真的不明白这是如何解析的。 Why does the second example return False?为什么第二个示例返回 False?

>>> 1 in [1,0]             # This is expected
True
>>> 1 in [1,0] == True     # This is strange
False
>>> (1 in [1,0]) == True   # This is what I wanted it to be
True
>>> 1 in ([1,0] == True)   # But it's not just a precedence issue!
                           # It did not raise an exception on the second example.

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

Thanks for any help.谢谢你的帮助。 I think I must be missing something really obvious.我想我一定错过了一些非常明显的东西。


I think this is subtly different to the linked duplicate:我认为这与链接的副本略有不同:

Why does the expression 0 < 0 == 0 return False in Python? 为什么表达式 0 < 0 == 0 在 Python 中返回 False? . .

Both questions are to do with human comprehension of the expression.这两个问题都与人类对表达的理解有关。 There seemed to be two ways (to my mind) of evaluating the expression.似乎有两种评估表达式的方法(在我看来)。 Of course neither were correct, but in my example, the last interpretation is impossible.当然,两者都不正确,但在我的例子中,最后一种解释是不可能的。

Looking at 0 < 0 == 0 you could imagine each half being evaluated and making sense as an expression:查看0 < 0 == 0你可以想象每一半都被评估并作为一个表达式有意义:

>>> (0 < 0) == 0
True
>>> 0 < (0 == 0)
True

So the link answers why this evaluates False :所以链接回答了为什么这会评估False

>>> 0 < 0 == 0
False

But with my example 1 in ([1,0] == True) doesn't make sense as an expression, so instead of there being two (admittedly wrong) possible interpretations, only one seems possible:但是对于我1 in ([1,0] == True)作为表达式没有意义,因此没有两种(公认错误)可能的解释,似乎只有一种可能:

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

Python actually applies comparison operator chaining here. Python 实际上在这里应用了比较运算符链接。 The expression is translated to表达式被翻译成

(1 in [1, 0]) and ([1, 0] == True)

which is obviously False .这显然是False

This also happens for expressions like这也发生在像这样的表达式上

a < b < c

which translate to这转化为

(a < b) and (b < c)

(without evaluating b twice). (不评估b两次)。

See the Python language documentation for further details.有关更多详细信息,请参阅Python 语言文档

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

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