为什么在Python中[] == False的结果为False,但0 == False的结果为True?

时间:2018-11-21 12:50:02

标签: python boolean equality

我是Python的新手,不了解以下行为:

为什么要声明

[] == False 

即使一个空列表是虚假的,也要评估为假?

还有更多示例-在许多其他情况下,空列表的行为似乎是虚假的,只是[[] == 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)有关,但无法真正理解这是否正确以及为什么。

1 个答案:

答案 0 :(得分:2)

因为虚假不是False。虚假的意思是

bool(some_object) is False

所以

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