不使用lambda:
from operator import mulreduce(mul, list, 1)
更好,更快。使用python 2.7.5
from operator import mulimport numpy as npimport numexpr as ne# from functools import reduce # python3 compatibilitya = range(1, 101)%timeit reduce(lambda x, y: x * y, a) # (1)%timeit reduce(mul, a) # (2)%timeit np.prod(a)# (3)%timeit ne.evaluate("prod(a)") # (4)在以下配置中:
a = range(1, 101) # Aa = np.array(a) # Ba = np.arange(1, 1e4, dtype=int) #Ca = np.arange(1, 1e5, dtype=float) #D
python 2.7.5的结果
| 1 | 2 | 3 | 4 |------- + ----------- + ----------- + ----------- + ------ ----- + 20.8 µs 13.3 µs 22.6 µs 39.6 µs B 106 µs 95.3 µs 5.92 µs 26.1 µs C 4.34毫秒3.51毫秒16.7微秒38.9微秒 D 46.6毫秒38.5毫秒180 µs 216 µs
结果:
np.prod如果
np.array用作数据结构,则速度最快(小型阵列为18x,大型阵列为250x)
使用python 3.3.2:
| 1 | 2 | 3 | 4 |------- + ----------- + ----------- + ----------- + ------ ----- + 23.6 µs 12.3 µs 68.6 µs 84.9 µs B 133 µs 107 µs 7.42 µs 27.5 µs C 4.79毫秒3.74毫秒18.6微秒40.9微秒 D 48.4毫秒36.8毫秒187微秒214微秒
python 3更慢吗?



