如何在循环中更新多个Numpy数组

问题描述:

我想在一个循环中更新(在每个元素之前添加其他元素)许多numpy数组,而不必为每个重复重复代码.

I would like to update (prepend each one with additional elements) many numpy arrays in a loop, without having to repeat the code for each one.

我尝试创建所有数组的列表,并遍历该列表中的项目并更新每个列表,但这并没有改变原始数组.

I tried creating a list of all the arrays and looping through the items in that list and updating each one, but that doesn't change the original array.

import numpy as np
arr01 = [1,2,3]
arr02 = [4,5,6]
arr99 = [7,8,9]
print('initial arr01', arr01)
arraylist = [arr01, arr02, arr99]
for array in arraylist:
    array = np.concatenate((np.zeros(3, dtype=int), array))
    print('array being modified inside the loop', array)
print('final arr01', arr01)

在示例代码中,我希望将arr01,arr02,arr03都修改为带零的前缀.

In the sample code, I expected arr01, arr02, arr03 to all be modified with the prepended zeros.

array = np.concatenate((np.zeros(3,dtype = int),array))不会更改当前数组,但创建一个新数组,并将其存储在变量 array 中.因此,对于该解决方案,您必须更改数组本身的值,这可以通过 array [:] 完成.

array = np.concatenate((np.zeros(3, dtype=int), array)) does not change the current array but creates a new one and stores it inside the variable array. So for the solution you have to change the values of the array itself, which can be done with array[:].

这意味着您唯一要做的更改就是替换这一行

That means the only change you would have to make is replacing this one line

array[:] = np.concatenate((np.zeros(3, dtype=int), array))

所以您的正确解决方案是

So your correct solution would be

import numpy as np
arr01 = [1,2,3]
arr02 = [4,5,6]
arr99 = [7,8,9]
print('initial arr01', arr01)
arraylist = [arr01, arr02, arr99]
for array in arraylist:
    array[:] = np.concatenate((np.zeros(3, dtype=int), array))
    print('array being modified inside the loop', array)
print('final arr01', arr01)