问题
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)
In the sample code, I expected arr01, arr02, arr03 to all be modified with the prepended zeros.
回答1:
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)
来源:https://stackoverflow.com/questions/57403239/how-to-update-multiple-numpy-arrays-in-a-loop