[英]after assigning a variable to a function. Why does the variable change every time the function is executed?
当我将变量X
分配给 function ( f
) 时,它的 output 是一个列表。 每次我在项目的任何地方执行 function f
后,变量X
都会发生变化。
该项目是关于强化学习的。 我无法在环境中记录我的状态。 当我 append 访问状态到名为state_history
的列表时,所有附加状态将在每次运行environment
function 后发生变化,并且所有状态都转换为最后一个 state。 我在这里写了一个伪代码,这样你就可以重新生成我的问题。
# this function takes current state in dictionary format, increment it's value and returns next state
def env_(current_state):
nex_state=current_state['current state'] +1
current_state['current state']=nex_state
return current_state
# i run function 10 times
state_history=[]
# initializing state
initial_state={}
initial_state['current state']=0
for i in range(10):
nex_state=env_(initial_state)
state_history.append(nex_state)
initial_state=nex_state
print(state_history)
结果如下:所有附加状态都转换为最后一个 state。
[{'current state': 10}, {'current state': 10}, {'current state': 10}, {'current state': 10}, {'current state': 10}, {'current state': 10}, {'current state': 10}, {'current state': 10}, {'current state': 10}, {'current state': 10}]
预期的结果是:
[{'current state': 1}, {'current state': 2}, {'current state': 3}, {'current state': 4}, {'current state': 5}, {'current state': 6}, {'current state': 7}, {'current state': 8}, {'current state': 9}, {'current state': 10}]
这里因为 next_State 每次都在变化,当追加到列表中时,它会随着更新的 next_state 而变化,而不是添加到已经创建的列表中,这是因为,您正在追加主列表而不是它的副本。 所以尝试附加 next_state 的副本。 或者你可以用 extend() function 代替 append 的 go。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.