当我在寻找答案时这个问题 https://stackoverflow.com/questions/9201445/python-best-way-to-keep-track-of-results-from-loop,我发现我不明白自己的答案。
我真的不明白这是如何解析的。为什么第二个示例返回 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 . https://stackoverflow.com/questions/6074018/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