最佳答案
检查列表是否包含奇数的两种类似方法:
any(x % 2 for x in a)
any(True for x in a if x % 2)
使用 a = [0] * 10000000
计时结果(每次5次,以秒为单位) :
0.60 0.60 0.60 0.61 0.63 any(x % 2 for x in a)
0.36 0.36 0.36 0.37 0.37 any(True for x in a if x % 2)
为什么第二条路的速度几乎是第二条路的两倍?
我的测试代码:
from timeit import repeat
setup = 'a = [0] * 10000000'
expressions = [
'any(x % 2 for x in a)',
'any(True for x in a if x % 2)',
]
for expression in expressions:
times = sorted(repeat(expression, setup, number=1))
print(*('%.2f ' % t for t in times), expression)