我作为“puzzle”传递给函数的列表正在被修改,我希望函数保持不变。在
"""moveDown() works by swapping the empty space with the block above it."""
def moveDown(xPosition, yPosition, puzzle):
returnPuzzle = list()
returnPuzzle.append(puzzle)
returnPuzzle = returnPuzzle[0]
if(puzzle[yPosition][xPosition]!=0): # is space we are moving the block into not empty?
return -1
if(yPosition-1<0):
return -1
print puzzle
#swap
returnPuzzle[yPosition][xPosition] = returnPuzzle[yPosition-1][xPosition]
returnPuzzle[yPosition-1][xPosition] = 0
print puzzle
return returnPuzzle
第一条print
语句返回传递给函数的原始puzzle
,但第二条语句修改了它,好像它在处理returnPuzzle
,而不是{
第一次打印:[[2, 1, 3], [6, 4, 5], [8, 7, 0]]
{cd6>第二个:^打印
因此,您创建一个列表,向其添加一个值,然后从列表中检索该值-这没有任何效果,这与直接访问
^{pr2}$puzzle
完全相同。要制作一个可以修改而不影响原始列表的副本,请使用:(这是一个列表切片,使用列表开头和结尾的默认值。)
由于
puzzle
是一个2d列表,因此需要构造它的副本,以避免在复制过程中保留对内部列表的引用。在正如其他答案所述,您只是将
puzzle
分配给returnPuzzle
。因为它是一个嵌套的列表,所以你需要做一个所谓的“深层拷贝”;其他的答案是指一个浅拷贝,你复制了这个列表,但是列表中的项目仍然是相同的。这意味着您将得到一个新的外部列表,其中包含相同的内部列表。既然你要改变内部列表,你也需要一个副本。在最简单的方法是使用
copy
模块:相关问题 更多 >
编程相关推荐