我有以下程序写作三为环插入一行(蟒蛇)
import numpy as np
X = np.asarray([ [2,3,4,5,1,1,1],
[1,2,3,4,1,1,1],
[3,3,3,3,1,1,1]])
Nrows=X.shape[0]
Ncols1=X.shape[1]
cols=np.asarray([[1,3]])
Ncols2=cols.shape[1]
Y = np.ndarray(shape=(Nrows,Ncols2))
for i in range(Nrows):
for j in range(Ncols2):
sum=0
for k in range(Ncols1):
sum=sum+np.exp(-(X[i,k]-X[i,cols[0,j])**2)
Y[i,j]=sum
我想减少三个环路成一行。这里的动机部分是为了加速考虑,部分是为了练习python技能。
所以,我可以写它把它变成两个循环:
for i in range(Nrows):
for j in range(Ncols1):
Y[i,j]=np.sum(np.exp(-(X[i,]-X[i,cols[0,j]])**2))
我可以写它把它变成一个循环:
for i in range(Nrows):
Y[i,]=map(lambda j: np.sum(np.exp(-(X[i,]-X[i,cols[0,j]])**2)),range(Ncols2))
但我无法弄清楚如何把它变成一条线。我的直觉是尝试
Y[:,]=map(lambda j: np.sum(np.exp(-(X[:,]-X[:,cols[0,j]])**2)),range(Ncols2))
但这种失败“ValueError异常:操作数无法与形状(3,7)(3)一起播出的”
任何帮助将是非常赞赏。
-Nick
我不确定是否将您的for循环冷凝为一条线会更有效率。但我相信你最终会得到一个非常复杂的混乱。 –
我同意@leaf所说的 – alfasin
不要编写你不能理解的代码。微观优化不会有太大的帮助。不好的做法 – 2016-12-16 18:37:18