简体   繁体   English

Python-如果不更改内部变量的值,为什么要更新内部循环的变量?

[英]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.

相关问题 Python为什么如果更改循环内的值,循环行为不会改变 - Python why loop behaviour doesn't change if I change the value inside loop 在 Python for 循环中获取更新的 object 值 - Getting an updated object value inside a Python for loop 变量在线程中更新,但更新后的值不反映在循环内 - Variable is updated in a thread but updated value does not reflect inside a loop 为什么当我使用 integer 索引但在 Django 模板引擎的循环内不使用可迭代变量时它会起作用 - why it's works when I use a integer index but don't whit a i itterable variable inside a loop in Django template engine 无法在“with”块内更改函数变量的值 python - Can't change a value of a function's variable inside a "with" block python 为什么在递归 python function 中没有更新 function 参数? - Why are the function parameters not being updated inside recursive python function? Jinja2:更改循环内变量的值 - Jinja2: Change the value of a variable inside a loop 为什么我不能从函数内部更改全局变量? - Why can't I change a global variable from inside a function? 更改变量 INSIDE 变量 python 的值 - Change value of variable INSIDE a variable python 为什么不使用 python 中的 function 里面的变量值 - Why doesn't use the variable value inside the function in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM