首页 > 解决方案 > Updating a python array without loops?

问题描述

I have a recursive relation, that I want to update without using loops for speed.

For example

import numpy as np
x=np.array([1,0,0,0,0])
x[1:]=(1+x[0:len(x)-1])**2.

This returns [1,4,1,1,1] for x, but I want [1,4,25,676,458329]. I know this can be done with a loop, but I'm really trying to avoid loops.

For example,

for i in range(1,len(x)):
    x[i]=(1+x[i-1])**2.

will return [1,4,25,676,458329]

标签: pythonlistnumpy

解决方案


>>> import numpy as np
>>> x=np.array([1,0,0,0,0])
>>> x[1:]=1
>>> x
array([1, 1, 1, 1, 1])

推荐阅读