[当我查看this question的答案时,我发现自己听不懂自己的答案。
我不太了解如何对此进行解析。为什么第二个示例返回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
感谢您的帮助。我想我一定会错过一些非常明显的东西。
我认为这与链接的重复项有细微的不同:
Why does the expression 0 < 0 == 0 return False in Python?。
这两个问题都与人类对表达的理解有关。在我看来,似乎有两种评估表达方式的方法。当然,两者都不正确,但是在我的示例中,最后的解释是不可能的。
看着0 < 0 == 0
,您可以想象每个被评估的部分都可以表达为有意义:
>>> (0 < 0) == 0
True
>>> 0 < (0 == 0)
True
因此,链接回答了为什么它计算False
:
>>> 0 < 0 == 0
False
但是在我的示例中,1 in ([1,0] == True)
作为表达式没有意义,因此,除了有两种(公认错误的)可能的解释之外,似乎只有一种可能:
>>> (1 in [1,0]) == True
Python实际上在这里应用比较运算符链接。该表达式翻译为
(1 in [1, 0]) and ([1, 0] == True)
显然是False
。
[对于类似表达式也是如此
a < b < c
翻译成
(a < b) and (b < c)
((不评估b
两次)。
请参阅Python language documentation了解更多详细信息。