目标
我想使用 map 函数计算总和。
通过使用以下示例数据:
X = [[2,3,4,5,6],[1,4,5,3,5]]
Y = [8.5,9.6]
这是我目前得到的:
import numpy as np
X = np.array([[2,3,4,5,6],[1,4,5,3,5]])
Y = np.array([8.5,9.6])
summation = X[0].dot(Y[0]) + X[1].dot(Y[1])
或
summation = np.sum(X.T * Y, axis=-1)
编辑:性能比较
t0 = time.time()
print sum(map(lambda x: x*Y[np.where(X==x)[0][0]], X))
t1= time.time()-t0
print t1
0.000971078872681
t0 = time.time()
print X[0].dot(Y[0]) + X[1].dot(Y[1])
t1= time.time()-t0
print t1
0.000860929489136
t0 = time.time()
print X.T.dot(Y)
t1= time.time()-t0
print t1
0.000858068466187
t0 = time.time()
print np.sum(X.T * Y, axis=-1)
t1= time.time()-t0
print t1
0.000848054885864
t0 = time.time()
print summation(X,Y)
t1= time.time()-t0
print t1
0.00386810302734
最快的解决方案是用 map 函数求和,然后是 np.sum,最慢的也是 map 函数。
请您参考如下方法:
你也试试这个,虽然这不是“最干净”的方法:
X = np.array([[2,3,4,5,6],[1,4,5,3,5]])
Y = np.array([8.5,9.6])
def summation(X, Y):
return sum(map(lambda x, y: x*y, X, Y))
print(summation(X,Y))
结果是:
[ 26.6 63.9 82. 71.3 99. ]
