[英]Python - Why backup variable inside loop is being updated if I don't change it value inside?
I want to set the values of matrix W in Wo. 我想在Wo中设置矩阵W的值。 Then, I will go inside a loop and do operations with W. At the end of the loop, I want to restore it to Wo, but I am getting the opposite result, Wo is becoming Wo.
然后,我将进入一个循环并使用W进行操作。在循环的最后,我想将其还原到Wo,但是得到的结果却相反,Wo变成了Wo。
How is that possible? 那怎么可能? How can I accomplish what I want?
我该如何完成我想要的? I have also tried defining Wo as a global but no result
我也曾尝试将Wo定义为全局,但没有结果
W = np.random.rand(5, 10)
global Wo
Wo = W # Back up for the initial values of W
for k in range(0, K):
for j in range(0, m): # For every hidden node
for i in range(0, n): # For every connection
# Operations (W get changed)
W = Wo
Then, if I check the value of Wo has been modified, in a way that Wo == W is always True. 然后,如果我检查Wo的值已被修改,则Wo == W始终为True。
What am I missing? 我想念什么?
Thanks in advance 提前致谢
To accomplish what you want, you need a deep copy. 要完成您想要的工作,您需要一个深层副本。 Otherwise you only create a reference to the same memory.
否则,您只能创建对相同内存的引用。
import numpy as np
import copy as cp
W = np.random.rand(5, 10)
global Wo
Wo = cp.deepcopy(W) # Back up for the initial values of W
for k in range(0, K):
for j in range(0, m): # For every hidden node
for i in range(0, n): # For every connection
# Operations (W get changed)
W = cp.deepcopy(Wo)
All items in Python are references so if you change one reference other will change too Python中的所有项目都是引用,因此如果您更改一个引用,其他内容也会更改
l = []
global l_global
l_global = l
for i in range(1, 10):
l.append(i)
print(l)
print(l_global)
Does it make sense now for your case? 现在对您的情况有意义吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.