简体   繁体   English

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

[英]how to check whether list contains only None in python

l=[None,None]

是否有一个函数检查列表l是否只包含None?

If you mean, to check if the list l contains only None, 如果你的意思是,检查列表l是否只包含None,

if all(x is None for x in l):
  ...
L == [None] * len(L)

is much faster than using all() when L is all 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

Try any() - it checks if there is a single element in the list which is considered True in a boolean context. 尝试any() - 它检查列表中是否有一个在布尔上下文中被视为True元素。 None evaluates to False in a boolean context, so any(l) becomes False . None在布尔上下文中求值为False ,因此any(l)变为False

Note that, to check if a list (and not its contents) is really None , if l is None must be used. 请注意,要检查列表(而不是其内容)是否真的为Noneif l is Noneif l is None必须使用。 And if not l to check if it is either None (or anything else that is considered False ) or empty. if not l要检查它是否是(或任何其他被认为是False )或空的。

I personally prefer making a set and then verifying if it is equal to a set with one element None : 我个人更喜欢制作一个set然后验证它是否等于具有一个元素的集合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

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 如果要检查列表本身是否为None,则可以使用type(varlist),它将返回None

you can do 你可以做

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

works. 作品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM