How to check if all items in the list are None?

In [27]: map( lambda f,p: f.match(p), list(patterns.itervalues()), vatids )
Out[27]: [None, <_sre.SRE_Match object at 0xb73bfdb0>, None]

The list can be all None or one of it is an re.Match instance. What one liner check can I do on the returned list to tell me that the contents are all None?

112496 次浏览
all(v is None for v in l)

will return True if all of the elements of l are None

注意,l.count(None) == len(l)要快得多,但是需要 l是一个实际的 list,而不仅仅是一个迭代器。

not any(my_list)

returns True if all items of my_list are falsy.

编辑 : 由于匹配对象总是真实的,而 None是假的,所以对于手边的情况,这将得到与 all(x is None for x in my_list)相同的结果。如 小不点的回答所示,使用 any()是目前为止最快的替代方案。

is_all_none = lambda L: not len(filter(lambda e: not e is None, L))


is_all_none([None,None,'x'])
False
is_all_none([None,None,None])
True

或者有点奇怪,但是:

a = [None, None, None]
set(a) == set([None])

或者:

if [x for x in a if x]: # non empty list
#do something

EDITED:

def is_empty(lVals):
if not lVals:
return True
for x in lVals:
if x:
return False
return True

Since Match objects are never going to evaluate to false, it's ok and much faster to just use not any(L)

$ python -m timeit -s"L=[None,None,None]" "all( v is None for v in L )"
100000 loops, best of 3: 1.52 usec per loop
$ python -m timeit -s"L=[None,None,None]" "not any(L)"
1000000 loops, best of 3: 0.281 usec per loop


$ python -m timeit -s"L=[None,1,None]" "all( v is None for v in L )"
100000 loops, best of 3: 1.81 usec per loop
$ python -m timeit -s"L=[None,1,None]" "not any(L)"
1000000 loops, best of 3: 0.272 usec per loop

我设法提出了一种使用 map的方法,这种方法还没有给出

博士

def all_none(l):
return not any(map(None.__ne__, l))


all_none([None, None, None]) # -> True
all_none([None, None, 8])    # -> False

解释

None.__ne__的使用比你第一眼看到的要奇怪一些。如果给定的对象不是 Nothing,则此方法返回 NotImplementedType对象。

您可能希望 NotImplemented将是 False的一个替身,但它也是真实的!这意味着跨集合使用 None.__eq__将为所有内容产生 thruthy 值。

list(map(None.__eq__, [None, None, 8]))
# -> [True, True, NotImplemented]


all(list(map(None.__eq__, [None, None, 8])))
# -> True

From the Python Docs:

默认情况下,除非对象的类定义了 返回 False 的 布尔()方法或者返回 Len()方法 返回零

相反,对于任何 None元素,None.__ne__返回 False,并且 NotImplementedType object for anything else:

list(map(None.__ne__, [None, None, 8]))
# -> [False, False, NotImplemented]

使用这个函数,您可以检查 any元素是否不是返回 TrueNone元素。我喜欢把这看作是两个独立的方法,如果这有助于心理否定体操。

def contains_truthy(l):
return any(map(None.__ne__, l))


def all_none(l):
return not contains_truthy(l)

我还没有用这个做过任何基准测试,但是正如这个线程中的其他人所提到的,not any将产生快速的结果。