更新没有循环的python数组?

时间:2019-06-28 14:44:15

标签: python list numpy

我有一个递归关系,我想在不使用循环提高速度的情况下进行更新。

例如

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

这将返回[1,4,1,1,1]的{​​{1}},但我想要x。我知道这可以通过循环来完成,但我实际上是在尝试避免循环。

例如,

[1,4,25,676,458329]

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

NumPy has a list of operations that work on arrays so you don't have to use an explicit for-loop to modify/update the array

其中一个是add,可以将一个数组与另一个数组相加,并且可以使用级联对数组的特定部分进行操作:

import numpy as np
x = np.array([1, 0, 0, 0, 0])
head = x[:1] # => [1]
tail = x[1:] # => [0, 0, 0, 0]
tail_values = np.full_like(tail, 1) # => [1, 1, 1, 1]
tail_plus_one = np.add(tail, tail_values) # => [0, 0, 0, 0] + [1, 1, 1, 1]
np.concatenate(head, tail_plus_one) # => [1] + [1, 1, 1, 1]

NumPy有a section in their user guide on iterating and modifying arrays and how to make it an efficient operation

答案 2 :(得分:0)

显然,这就是您想要做的:

In [30]: x = np.array([1,0,0,0,0])                                                                              
In [31]: for i in range(1,len(x)): 
    ...:     x[i] = (1+x[i-1])**2 
    ...:                                                                                                        
In [32]: x                                                                                                      
Out[32]: array([     1,      4,     25,    676, 458329])

许多ufunc实现了accumulate方法

In [33]: np.add.accumulate(np.arange(5))                                                                        
Out[33]: array([ 0,  1,  3,  6, 10])
In [34]: np.multiply.accumulate(np.arange(1,6))                                                                 
Out[34]: array([  1,   2,   6,  24, 120])

它们如上所述进行迭代,但是在已编译的代码中进行迭代。但是,通常来说,您无法以相同的速度运行自己的Python函数。