如何在python中检查列表是否只包含None

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3583860/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:49:33  来源:igfitidea点击:

how to check whether list contains only None in python

python

提问by goblin2986

l=[None,None]

is there a function that checks whether list l contains only None or not?

有没有检查列表 l 是否只包含 None 的函数?

采纳答案by kennytm

If you mean, to check if the list lcontains only None,

如果您的意思是检查列表是否l仅包含 None,

if all(x is None for x in l):
  ...

回答by Alexander Gessler

Try any()- it checks if there is a single element in the list which is considered Truein a boolean context. Noneevaluates to Falsein a boolean context, so any(l)becomes False.

尝试any()- 它检查列表中是否有一个True在布尔上下文中被考虑的元素。在布尔上下文中None计算为False,因此any(l)变为False

Note that, to check if a list (and not its contents) is really None, if l is Nonemust be used. And if not lto check if it is either None (or anything else that is considered False) or empty.

请注意,要检查列表(而不是其内容)是否真的是Noneif l is None必须使用。并if not l检查它是 None (或任何其他被考虑的东西False)还是空的。

回答by John La Rooy

L == [None] * len(L)

is much faster than using all() when L isall None

比使用所有的()当L快得多所有无

$ python -m timeit -s'L=[None]*1000' 'all(x is None for x in L)'
1000 loops, best of 3: 276 usec per loop
$ python -m timeit -s'L=[None]*1000' 'L==[None]*len(L)'
10000 loops, best of 3: 34.2 usec per loop

回答by powerrox

If you want to check if the members of the list are None, then you can loop over the items and check if they are None

如果要检查列表的成员是否为 None,则可以遍历项目并检查它们是否为 None

If you want to check if list itself is None, you can use type(varlist) and it will return None

如果你想检查 list 本身是否为 None,你可以使用 type(varlist) 并且它会返回 None

you can do

你可以做

if (lst == None): ... print "yes"

if (lst == None): ... 打印“是”

works.

作品。

回答by Filippo Vitale

I personally prefer making a setand then verifying if it is equal to a set with one element None:

我个人更喜欢制作 aset然后验证它是否等于具有一个元素的集合None

set(l) == {None}

assert set([None, None, None]) == {None}
assert set([None, 2, None])    != {None}

Not the fastest but still faster than the all(...)implementation:

不是最快的,但仍然比all(...)实现快:

$ python -m timeit -s'L=[None]*1000' 'all(x is None for x in L)'
10000 loops, best of 3: 59 usec per loop
$ python -m timeit -s'L=[None]*1000' 'set(L)=={None}'
100000 loops, best of 3: 17.7 usec per loop
$ python -m timeit -s'L=[None]*1000' 'L==[None]*len(L)'
100000 loops, best of 3: 7.17 usec per loop