性能介于not in 和all 之间。请注意,对于这种特殊情况,带有 all 的明智(首选)版本最终会执行缓慢 - 但至少比 min 领先
def assert_all_not_none(l):
for x in l:
if x is None:
return False
return True
编辑:这里有一些基准供有兴趣的人参考
from timeit import timeit
def all_not_none(l):
for b in l:
if b is None:
return False
return True
def with_min(l):
min(l, key=lambda x: x is not None, default=False)
def not_in(l):
return None not in l
def all1(l):
return all(i is not None for i in l)
def all2(l):
return all(False for i in l if i is None)
def all_truthy(l):
return all(l)
def any1(l):
return any(True for x in l if x is None)
l = ['a', 'b', 'c'] * 20_000
n = 1_000
# 0.63
print(timeit("all_not_none(l)", globals=globals(), number=n))
# 3.41
print(timeit("with_min(l)", globals=globals(), number=n))
# 1.66
print(timeit('all1(l)', globals=globals(), number=n))
# 0.63
print(timeit('all2(l)', globals=globals(), number=n))
# 0.63
print(timeit('any1(l)', globals=globals(), number=n))
# 0.26
print(timeit('all_truthy(l)', globals=globals(), number=n))
# 0.53
print(timeit('not_in(l)', globals=globals(), number=n))
出乎意料的获胜者:all(list)。因此,如果您确定列表不会包含空字符串或零等虚假值,那么这样做没有错。