你可以做:
>>> l = [True, False, True]
>>> False in map(bool, l)
True
回想一下,map
在Python 3中是生成器。对于Python 2,您可能要使用imap
Mea Culpa:确定这些时间之后,我提供的方法是最慢的
最快的就是not all(l)
或者not next(filterfalse(bool, it), True)
只是一个愚蠢的itertools变体。使用Jack Aidleys解决方案。
时间码:
from itertools import filterfalse
def af1(it):
return not all(it)
def af2(it):
return any(not i for i in it)
def af3(iterable):
for element in iterable:
if not element:
return True
return False
def af4(it):
return False in map(bool, it)
def af5(it):
return not next(filterfalse(bool, it), True)
if __name__=='__main__':
import timeit
for i, l in enumerate([[True]*1000+[False]+[True]*999,
[False]*2000,
[True]*2000],
start=1):
print("case:", i)
for f in (af1, af2, af3, af4, af5):
print(" ",f.__name__, timeit.timeit("f(l)", setup="from __main__ import f, l", number=100000), f(l) )
结果:
case: 1
af1 0.45357259700540453 True
af2 4.538436588976765 True
af3 1.2491040650056675 True
af4 8.935278153978288 True
af5 0.4685744970047381 True
case: 2
af1 0.016299808979965746 True
af2 0.04787631600629538 True
af3 0.015038023004308343 True
af4 0.03326922300038859 True
af5 0.029870904982089996 True
case: 3
af1 0.8545824179891497 False
af2 8.786235476000002 False
af3 2.448748088994762 False
af4 17.90895140200155 False
af5 0.9152941330103204 False