追加到列表会复制最后一项 python



我正在尝试使用路径查找算法,我希望它一一打印所有步骤,这是一个简化的代码,只有重要部分。出于某种原因,这会打印出 7 个相同的级别,这些级别只是最后一步,但我需要它来打印出所有步骤。问题似乎出在附加部分,但我不知道如何解决。

level = [
[">","#"," "," "],
[" ","#","#"," "],
[" "," ","#"," "],
["#"," "," "," "],
]
cycle = [[0,0],[1,0],[2,1],[3,2],[3,3],[2,3],[1,3],[0,2]]
output = []
for i in range(len(cycle)-1):
level[cycle[i  ][0]][cycle[i  ][1]] = " "
level[cycle[i+1][0]][cycle[i+1][1]] = ">"
output.append(level)
for i in output:
for ii in i:
print(ii)
print()

我需要有人为我解决这个问题,因为这个网站上的任何内容都不适用于我的确切问题

import copy
level = [
[">","#"," "," "],
[" ","#","#"," "],
[" "," ","#"," "],
["#"," "," "," "],
]
cycle = [[0,0],[1,0],[2,1],[3,2],[3,3],[2,3],[1,3],[0,2]]
output = []
for i in range(len(cycle)-1):
level_copy = copy.deepcopy(level)  
level_copy[cycle[i  ][0]][cycle[i  ][1]] = " "
level_copy[cycle[i+1][0]][cycle[i+1][1]] = ">"
output.append(level_copy)
for i in output:
for ii in i:
print(ii)
print()

当您在循环中执行level[cycle[i ][0]][cycle[i ][1]] = " "时,您指的是第一行中定义的相同级别对象。因此,您最终确实会多次放置级别,但它们都引用了相同的对象,因此包含在循环的最后一次迭代中写入的值。

level = []
output = []
for i in range (2):
if i == 0:
level.append(1) 
level.append(2)
else
level.append(24)
level.append(25)
output.append(level)
i = 0: Start: level=[], end: level=[1,2]
i = 1: Start: level=[1,2] end: level=[1,2,24,25] // Observe that it starts with state left at end of first iteration as we are still referring to the same object in memory referred to by variable level. 

最新更新