检查None 或null 的Pythonic 方法是:
if element:
# This is not null
if not element:
# This is null
关于if not x和if x == None的区别有一个很detailed answer。
编辑 1:
结合评论和其他答案:
错误值
Python 将以下内容视为False source:
None
False
- 任何数字类型的零,例如:
0、0L、0.0、0j
- 任何空序列,例如:
'', (), []
- 任何空映射,例如:
{}
- 用户定义类的实例,如果该类定义了
__nonzero__()或 __len__()方法,当该方法返回整数zero或布尔值False
真值
所有其他值都被视为True。
你的问题:
如果您确实在检查您的列表中是否存在None ([1,2,None,4,5,6]),那么@Poke 的答案是正确的:
>>> lst = [1, 2, None, 4, 5, 6]
>>> None in lst
True
如果您想检查元素是否仅 None,那么 @esauro 在 cmets 中是正确的:
>>> lst = [1, 2, None, 4, 5, 6]
>>> for x in lst:
... if not x:
... print(x)
None
但如果您的 lst 包含 0 (lst = [0, 1, 2, 4, 5, 6]),那么您的输出将是 0。
解决此问题的唯一方法是明确检查if element is None或if element is not None。