为什么“[] == False"当“if not []"时评估为 False成功了吗? [英] Why does "[] == False" evaluate to False when "if not []" succeeds?
问题描述
我问这个是因为我知道检查列表是否为空的pythonic方法如下:
my_list = []如果不是 my_list:打印计算机说不"别的:# my_list 不为空打印计算机说是"
将打印计算机说不
,等等.所以这导致我用False
真值识别[]
;但是,如果我尝试直接"比较 [] 和 False,则会得到以下结果:
等等……
这是怎么回事?我觉得我错过了一些非常明显的东西.
if
语句在布尔上下文中评估所有内容,就像对 bool()
内置函数.
以下是您实际检查 if
语句将如何评估事物的方法:
请参阅关于真值测试的文档,考虑空列表false,但这并不意味着它们等同于 False
.
PEP 285 也有一些关于为什么以这种方式实现的很好的信息,请参阅Resolved Issues 部分中的最后一项,用于专门处理 x == True
和 x == False
的部分.
对我来说最有说服力的方面是 ==
通常是可传递的,所以 a == b
和 b == c
意味着 <代码>a == c.因此,如果这是您期望的方式并且 [] == False
为真且 '' == False
为真,那么人们可能会假设 [] ==''
应该是真的(即使它显然不应该在没有隐式类型转换的语言中).
I'm asking this because I know that the pythonic way to check whether a list is empty or not is the following:
my_list = []
if not my_list:
print "computer says no"
else:
# my_list isn't empty
print "computer says yes"
will print computer says no
, etc. So this leads me to identify []
with False
truth-values; however, if I try to compare [] and False "directly", I obtain the following:
>>> my_list == False
False
>>> my_list is False
False
>>> [] == False
False
etc...
What's going on here? I feel like I'm missing something really obvious.
The if
statement evaluates everything in a Boolean context, it is like there is an implicit call to the bool()
built-in function.
Here is how you would actually check how things will be evaluated by an if
statement:
>>> bool([])
False
>>> bool([]) == False
True
See the documentation on Truth Value Testing, empty lists are considered false, but this doesn't mean they are equivalent to False
.
PEP 285 also has some excellent information on why it was implemented this way, see the very last bullet in the Resolved Issues section for the part that deals with x == True
and x == False
specifically.
The most convincing aspect to me is that ==
is generally transitive, so a == b
and b == c
implies a == c
. So if it were the way you expected and [] == False
were true and '' == False
were true, one might assume that [] == ''
should be true (even though it obviously should not be in a language without implicit type conversion).
这篇关于为什么“[] == False"当“if not []"时评估为 False成功了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!