Python 对数组等对象拷贝默认采用的方法是引用传递,即地址传递,修改拷贝的值的时候原对象也会随之改变。
如:
origin = np.array([1,1,2,2,3,3,4,5])
filter_arr = [1,2,3]
for i in range(3):
temp = origin
print(origin)
print(temp)
temp[temp!=filter_arr[i]] = 0
print(temp)
print('-----------------')
Output:
[1 1 2 2 3 3 4 5]
[1 1 2 2 3 3 4 5]
[1 1 0 0 0 0 0 0]
-----------------
[1 1 0 0 0 0 0 0]
[1 1 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
-----------------
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
-----------------
我们可以看到这里并没有得到预期的数组结果,原因是这里的数组传递采用的是地址传递的方法,当我们改变 temp 数组时其实是对 temp 指向地址对象的改变,由于 temp 和 origin 指向的是同一地址,改变 temp 数组的内容, origin 数组的内容也随之改变。
好在我们可以通过 copy() 进行深拷贝,即拷贝 numpy 对象中的数据,而不是地址。
origin = np.array([1,1,2,2,3,3,4,5])
filter_arr = [1,2,3]
for i in range(3):
#使用narray.copy()进行深拷贝,即拷贝numpy对象中的数据,而不是地址
temp = origin.copy()
print(origin)
print(temp)
temp[temp!=filter_arr[i]] = 0
print(temp)
print('-----------------')
得到结果如下:
[1 1 2 2 3 3 4 5]
[1 1 2 2 3 3 4 5]
[1 1 0 0 0 0 0 0]
-----------------
[1 1 2 2 3 3 4 5]
[1 1 2 2 3 3 4 5]
[0 0 2 2 0 0 0 0]
-----------------
[1 1 2 2 3 3 4 5]
[1 1 2 2 3 3 4 5]
[0 0 0 0 3 3 0 0]
-----------------