为什么(1 in [1,0] == True)结果为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
谢谢大家的帮助。我觉得我一定是漏掉了一些很明显的东西。
我觉得这个问题和之前的重复问题有些微妙的不同:
为什么表达式 0 < 0 == 0 在 Python 中返回 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
1 个回答
204
在这里,Python 实际上使用了比较运算符的链式比较。这个表达式被转换成了
(1 in [1, 0]) and ([1, 0] == True)
显然这个结果是 False
。
类似的情况也会出现在这样的表达式中
a < b < c
它们会被转换成
(a < b) and (b < c)
(而且不会重复计算 b
两次)。
想了解更多细节,可以查看 Python 的官方文档。