This question already has answers here:
Empty list boolean value
(3个答案)
12个月前关闭。
我对Python比较陌生,不了解以下行为:
为什么这个声明
[] == False

评估为false,即使空列表是falsy?
这里有更多的例子-在许多其他情况下,空列表的行为似乎是错误的,只是不在[]==False。。。
>>> 0 == False                # what I'd expect
True
>>> not []                    # what I'd expect
True
>>> bool([])                  # what I'd expect
False
>>> [] == True                # what I'd expect
False
>>> [] == False               # unexpected
False
>>> bool([]) == False         # why does it evaluate to True again now?
True
>>> ([]) == (bool([]))        # unexpected
False
>>> (not []) == (not bool([]) # apparently adding 'not' makes it behave as expected again - why?
True

有人能给我解释一下吗?如何对这些陈述进行内部评估?我有一种感觉,这可能与链接比较(see e.g. here)有关,但无法真正理解这是否正确以及原因。

最佳答案

因为falsy不是False。虚伪的意思是

bool(some_object) is False

所以,
>>> bool([]) is False
True
>>> bool({}) is False
True
>>> bool(0) is False
True

08-28 04:31