检查 Python 列表中的任何项目是否为 None(但包括零)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28836378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if any item in Python list is None (but include zero)
提问by Bryan
I'm trying to do a simple test that returns True
if any of the results of a list are None
. However, I want 0
and ''
to not cause a return of True
.
我正在尝试做一个简单的测试,True
如果列表的任何结果是None
. 但是,我希望0
并且''
不会导致True
.
list_1 = [0, 1, None, 4]
list_2 = [0, 1, 3, 4]
any(list_1) is None
>>>False
any(list_2) is None
>>>False
As you can see, the any()
function as it is isn't being helpful in this context.
如您所见,该any()
函数在此上下文中没有帮助。
采纳答案by Martijn Pieters
For list
objects can simply use a membership test:
对于list
对象可以简单地使用成员资格测试:
None in list_1
Like any()
, the membership test on a list
will scan all elements but short-circuit by returning as soon as a match is found.
像 一样any()
, a 上的成员资格测试list
将扫描所有元素,但一旦找到匹配项就会返回短路。
any()
returns True
or False
, never None
, so your any(list_1) is None
test is certainly not going anywhere. You'd have to pass in a generator expression for any()
to iterate over, instead:
any()
返回True
or False
, never None
,所以你的any(list_1) is None
测试肯定不会去任何地方。你必须传入一个生成器表达式any()
来迭代,而不是:
any(elem is None for elem in list_1)
回答by Tom Cornebize
list_1 = [0, 1, None, 4]
list_2 = [0, 1, 3, 4]
any(x is None for x in list_1)
>>>True
any(x is None for x in list_2)
>>>False