8

我正在测试一个列表,看看它是否为空。通常我使用 len(list) == 0 并且我隐约记得不久前阅读过测试列表是否为空的正确方法是它是真还是假。

所以我试过 list is False,结果返回 False。也许我想使用 == ?不,这也返回了错误。list 为 True,返回 false 与 list == True 一样。

现在我很困惑,所以我快速搜索了一下,结果是:检查列表是否为空的最佳方法

最佳答案是:

if not a:
    print "List is empty"

所以我搜索了更多内容,最后在 python 手册中找到了 4.1 状态:

可以测试任何对象的真值,用于 if 或 while 条件或作为以下布尔运算的操作数。以下值被认为是错误的:

任何空序列,例如,''、()、[]。

现在我很困惑。如果我测试一个列表,就像不是列表一样,它工作正常。但是如果一个空列表是假的,那么如果列表是假的或者如果列表 == 假,我为什么不能这样做呢?

谢谢

4

4 回答 4

14

空列表不是 False,但是当您将其转换为布尔值时,它会转换为 False。对于字典、元组、字符串等也是如此:

>>> [] == False
False
>>> bool([]) == False
True
>>> {} == False
False
>>> bool({}) == False
True

当您将某些内容放在if子句的条件中时,它是用于测试的布尔值if。这就是为什么if someList与 相同if bool(someList)。同样,not foo布尔值不是,所以not []等于 True。

于 2012-07-31T02:38:11.773 回答
2

正如其他人所说,在 python bool([]) == False. python 程序员经常利用的一件事是运算符andor不(必然)返回真/假。考虑以下:

3 and 4  #returns 4
0 and 8  #returns 0 -- This is short-circuit evaluation
0 or 8   #returns 8
True or 0 #returns True -- This is short-circuit evaluation

[] or False #returns False
False or [] #returns []

语句中发生的情况if是条件按上述方式进行评估,然后 python 隐式调用bool结果——因此您可以将其视为:

if condition:

与以下内容相同:

if bool(condition):

就python而言。对于not运算符也是如此:

not condition

是一样的

not bool(condition)
于 2012-07-31T02:47:45.853 回答
1

mylist is False意思是“对象的名称与?mylist 完全相同False?”

mylist == False意思是“命名的对象是否mylist 等于 False

not mylist means "does the object named mylist behave falsily?


None of these are equivalent: 1 is not 1.0 but 1 == 1.0 and [] != False but not [] is True.

于 2012-07-31T02:57:19.187 回答
0

将列表与 进行比较False,并测试列表的真假并不完全相同。空列表不等于False,但False在布尔上下文中的行为。

这是另一种说法,可能有助于理解这一点:

print (bool([]) == False) # will print True
print ([] == False) # will print False
于 2012-07-31T02:39:27.427 回答