将列表附加到 python 列表
Append list to a python list
我正在尝试 运行 在具有四个等概率动作的二维网格上随机游走 [右 (1)、左 (-1)、向上 (1)、向下 (-1)] .随着随机游走者向前移动,我想将它的位置(x,y 坐标)存储在列表 totSteps 中。 x,y 坐标(即当前位置)将在每一步更新为变量 curr_loc。正如您在打印输出中看到的那样,第一个列表 (curr_loc) 是更新后的当前位置,第二个列表 ( totSteps) 应该包含到目前为止采取的步骤。采取了 5 个步骤,因此我们有 10 个输出。每次我将 curr_loc 附加到 totSteps;所有以前的坐标都被当前坐标替换。什么原因?
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)
The output of the code is given below:
>[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
.
的引用
我正在尝试 运行 在具有四个等概率动作的二维网格上随机游走 [右 (1)、左 (-1)、向上 (1)、向下 (-1)] .随着随机游走者向前移动,我想将它的位置(x,y 坐标)存储在列表 totSteps 中。 x,y 坐标(即当前位置)将在每一步更新为变量 curr_loc。正如您在打印输出中看到的那样,第一个列表 (curr_loc) 是更新后的当前位置,第二个列表 ( totSteps) 应该包含到目前为止采取的步骤。采取了 5 个步骤,因此我们有 10 个输出。每次我将 curr_loc 附加到 totSteps;所有以前的坐标都被当前坐标替换。什么原因?
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)
The output of the code is given below:
>[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
.