当我查看这个问题的答案时,我发现我自己的答案不理解。
我并不真正理解这是如何被解析的。为什么第二个例子返回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
感谢任何帮助。我认为我一定错过了什么非常明显的东西。
我认为这与链接的重复不同:
为什么在Python中表达式0 < 0 == 0返回False?.
这两个问题都与人类理解表达式有关。在我看来,似乎有两种评估表达式的方法。当然,两者都是不正确的,但在我的例子中,最后一种解释是不可能的。
观察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
==
的绑定比in
更紧密,因此[1,0] == True
首先被评估,然后将该结果馈送到1 in other_result
。 - Marc B