在Python中将列表追加到另一个列表的问题

时间:2020-03-11 13:30:12

标签: python

我是Python的新手,我正在做一个8题问题(我的第一个程序)。我在将列表追加到另一个列表时遇到问题。以下是我的代码的一部分。

def solvePuzzle(puzzle,path,visited):
   moveState = []

   if(init == goal):
       path.append(puzzle)
       return True;

   puzzleT = deepcopy(puzzle)
   visited.append(copy(puzzle))
   index = findBlankTile(puzzleT)
   moveState = moveTileChoice(puzzleT,visited,index)

   #move process

   for move in moveState:
       path.append(copy(puzzle))
       if(applyMove(move,puzzle,path,visited,index)):
           return True;
       else:
           path.remove()
           return False;

在套用移动功能中,当我将空白图块与拼图中的其他数字图块(下面的代码)交换时,“已访问”和“路径”列表中的所有值也都更改了,这不是我想要的。我的代码有什么错?

def applyMove(move,puzzle,path,visited,index):   
    row = index[0]
    col = index[1]
    if move == "Left":
        puzzle[row][col] , puzzle[row][col-1] = puzzle[row][col-1] , puzzle[row][col]
        return solvePuzzle(puzzle,path,visited)

    elif move == "Right":
        puzzle[row][col] , puzzle[row][col+1] = puzzle[row][col+1] , puzzle[row][col]
        return solvePuzzle(puzzle,path,visited)

    elif move == "Up":
        puzzle[row][col] , puzzle[row-1][col] = puzzle[row-1][col] , puzzle[row][col]
        return solvePuzzle(puzzle,path,visited)

    elif move == "Down":
        puzzle[row][col] , puzzle[row+1][col] = puzzle[row+1][col] , puzzle[row][col]
        return solvePuzzle(puzzle,path,visited)

    else:
        return False;

1 个答案:

答案 0 :(得分:0)

使用list.extend(seq),然后看看here