将list追加到python列表



我试图在一个二维网格上运行一个随机行走,具有四个等概率动作[右(1),左(-1),向上(1),向下(-1)]。当随机漫步器向前移动时,我想将其位置(x, y坐标)存储在列表totSteps。x、y坐标(即当前位置)将作为变量curr_loc在每一步中更新。。在打印的输出中可以看到,第一个列表(curr_loc))是更新后的当前位置,第二个列表(totSteps))应该包含到目前为止所采取的步骤。我们采取了5个步骤,因此我们有10个输出。每次我添加curr_loctotSteps;所有之前的坐标都被替换为当前的坐标。原因是什么?

steps = [1,-1,1,-1]
totSteps = [] # stores all the 5 steps taken but doesn't work 
# random walk with four steps left, right, 
# upward, downward on two dimensional grid
curr_loc = [0,0]
N = 5
for i in range(N):
ranNums = np.random.randint(0,4) # picks one of four actions 
if ranNums == 0 or ranNums == 1: # change x-coordinate
curr_loc[0] += steps[ranNums] # taking the step 
print(curr_loc) # current location of random walker 
totSteps.append(curr_loc)
print(totSteps) # append current location of random walker 
elif ranNums == 2 or ranNums == 3: # chanfe y-coordinate 
curr_loc[1] += steps[ranNums]
print(curr_loc)
totSteps.append(curr_loc) 
print(totSteps)

代码输出如下:

>[1, 0] # curr_loc
>[[1, 0]] # totSteps
>[1, -1]
>[[1, -1], [1, -1]]
>[1, 0]
>[[1, 0], [1, 0], [1, 0]]
>[1, -1]
>[[1, -1], [1, -1], [1, -1], [1, -1]]
>[0, -1]
>[[0, -1], [0, -1], [0, -1], [0, -1], [0, -1]]

进一步扩展@AndrejKesely的回答,当一个新的循环迭代开始时,你没有定义一个新的list对象,所以每当你改变curr_loc中的值时,因为你本质上是将curr_loc的另一个引用附加到totSteps,你有五个引用到同一个对象,这就是为什么你得到相同的值。

Andrej对curr_loc[:]的解决方案意味着你有效地复制了整个列表并存储它,而不是引用curr_loc

最新更新