import cProfile, numpy as np
from operator import add
A = np.random.rand(1000000)
B = np.random.rand(1000000)
>>> cProfile.run('C = map(add, A, B)')
3 function calls in 0.693 seconds
>>> cProfile.run('C = [a+b for a,b in izip(A,B)]')
2 function calls in 0.765 seconds
>>> cProfile.run('for i in np.arange(0,len(B),1): C[i] = A[i]+B[i]')
4 function calls in 1.971 seconds
使用
map
似乎比列表理解快得多:但正如@larsmans所说,使用矢量化解决方案将更快:
^{pr2}$既然你用的是
arange
,我想你是在用NumPy。尝试重写my_function
,使其接受两个数组而不是两个标量值,并使用矢量化操作。在如果需要访问两个列表的每个元素,如何避免循环?我不太明白你的问题。在
但你可以做得更简单一点。在Python 3中:
在python2中,最好使用
^{pr2}$相关问题 更多 >
编程相关推荐