问题描述
我在大型代码中发现了一个错误,并将问题简化为以下情况.
I found a bug in my large code, and I simplified the issue to the case below.
尽管在每个步骤中我都只更改w2
,但是当在每个步骤中我打印出w1
时,它也会被更改,因为在第一个循环的结尾我将它们分配为相等.我读过这篇文章,但是写了万一我写的w1 = w2[:]
可以解决问题,但不能解决
Although in each step I only change w2
, but when at each step I print out w1
, it is also changed, because end of the first loop I assign them to be equal.I read for this but there was written in case I make w1 = w2[:]
it will solve the issue but it does not
import numpy as np
import math
w1=np.array([[1,2,3],[4,5,6],[7,8,9]])
w2=np.zeros_like(w1)
print 'w1=',w1
for n in range(0,3):
for i in range(0,3):
for j in range(0,3):
print 'n=',n,'i=',i,'j=',j,'w1=',w1
w2[i,j]=w1[i,j]*2
w1=w2[:]
#Simple tests
# w=w2[:]
# w1=w[:]
# p=[1,2,3]
# q=p[:];
# q[1]=0;
# print p
推荐答案
问题是,当您将值从w2
分配回w1
时,实际上并没有将值从w1
传递给w2
,但是实际上您是将两个变量指向相同的对象.
The issue is that when you're assigning values back to w1
from w2
you aren't actually passing the values from w1
to w2
, but rather you are actually pointing the two variables at the same object.
您遇到的问题
w1 = np.array([1,2,3])
w2 = w1
w2[0] = 3
print(w2) # [3 2 3]
print(w1) # [3 2 3]
np.may_share_memory(w2, w1) # True
解决方案
相反,您将需要复制值.使用numpy数组有两种常见的方法.
Instead you will want to copy over the values. There are two common ways of doing this with numpy arrays.
w1 = numpy.copy(w2)
w1[:] = w2[:]
示范
w1 = np.array([1,2,3])
w2 = np.zeros_like(w1)
w2[:] = w1[:]
w2[0] = 3
print(w2) # [3 2 3]
print(w1) # [1 2 3]
np.may_share_memory(w2, w1) # False
这篇关于尽管更改了另一个数组,但一个numpy数组却意外更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!