简体   繁体   English

附加到列表复制最后一项python

[英]appending to a list copies the last item python

I am trying to use a path finding algorithm and I want it to print all the steps one by one, this is a simplified code with only the important parts.我正在尝试使用路径查找算法,我希望它一个一个打印所有步骤,这是一个仅包含重要部分的简化代码。 For some reason this prints out 7 same levels that are only the final step, but I need it to print out all of the steps.出于某种原因,这会打印出 7 个相同的级别,这些级别只是最后一步,但我需要它来打印出所有步骤。 The problem seems to be in the appending part, but I don't know how to fix it.问题似乎出在附加部分,但我不知道如何解决。

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()

I need someone to solve this problem for me, as anything on this site doesn't work in my exact problem我需要有人为我解决这个问题,因为这个网站上的任何东西都不能解决我的确切问题

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()

When you do level[cycle[i ][0]][cycle[i ][1]] = " " inside the loop, you are referring to the same level object defined in the first line.当您在level[cycle[i ][0]][cycle[i ][1]] = " "执行level[cycle[i ][0]][cycle[i ][1]] = " " ,您指的是第一行中定义的相同级别对象。 So you do end up putting level multiple times, but they all are referring to the same object and hence contain the value that was written in the last iteration of loop.所以你最终会多次放置 level,但它们都指向同一个对象,因此包含在循环的最后一次迭代中写入的值。

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. 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM