英文:
Using numpy to create a list more efficiently
问题
我有一个任务要使用numpy并从以下代码中删除循环:
F = np.zeros(2*N)
for i in range(N):
F[i] = v[N+i]
if(i == 0) or (i == N-1):
F[N+i] = 0
else:
F[N+i] = K*v[i+1]+v[i-1]-2*v[i]
我的方法是这样的:
np.append(v[-N:], [0], np.fromiter((K*v[i+1]+v[i-1]-2*v[i] for i in range(1,N-1))), [0])
然而,这仍然包含一个循环,感觉太复杂了。也许有一些代码可以让我更有效地/更好地完成这个任务吗?
谢谢
英文:
I have an assignment to use numpy and to remove loops from the following code:
F = np.zeros(2*N)
for i in range(N):
F[i] = v[N+i]
if(i == 0) or (i == N-1):
F[N+i] = 0
else:
F[N+i] = K*v[i+1]+v[i-1]-2*v[i]
My approach was along the lines of
np.append(v[-N:], [0], np.fromiter((K*v[i+1]+v[i-1]-2*v[i] for i in range(1,N-1))), [0])
However, this still contains a loop and feels too complex. Is there perhaps some code that would allow me to do this more efficiently / in a nicer way?
Thanks
答案1
得分: 2
下述内容为翻译好的部分:
# 向量计算可以消除for循环。对于`i == 1`,起始索引为`i+1`,`i-1`或`i`,终止索引对于`i == N-1`是相同的:
F = np.concatenate([v[N:], [0], K*v[2:N]+v[0:N-2]-2*v[1:N-1], [0]])
英文:
The for-loop can be eliminated by vector calculation. Start indices are i+1
, i-1
or i
for i == 1
and end indices are the same for i == N-1
:
F = np.concatenate([v[N:],[0], K*v[2:N]+v[0:N-2]-2*v[1:N-1], [0]])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论