使用numpy更高效地创建列表

huangapple go评论88阅读模式
英文:

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]])

huangapple
  • 本文由 发表于 2020年1月3日 19:41:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定