如何防止函数修改列表

2024-09-27 04:29:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我作为“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>第二个:^打印


Tags: the函数列表returnifspace语句block
3条回答
returnPuzzle = list()
returnPuzzle.append(puzzle)
returnPuzzle = returnPuzzle[0]

因此,您创建一个列表,向其添加一个值,然后从列表中检索该值-这没有任何效果,这与直接访问puzzle完全相同。要制作一个可以修改而不影响原始列表的副本,请使用:

^{pr2}$

(这是一个列表切片,使用列表开头和结尾的默认值。)

由于puzzle是一个2d列表,因此需要构造它的副本,以避免在复制过程中保留对内部列表的引用。在

def duplicate2dList(oldList):
    newList = []

    for l in oldList:
        newList.append(l[:])

    return newList

正如其他答案所述,您只是将puzzle分配给returnPuzzle。因为它是一个嵌套的列表,所以你需要做一个所谓的“深层拷贝”;其他的答案是指一个浅拷贝,你复制了这个列表,但是列表中的项目仍然是相同的。这意味着您将得到一个新的外部列表,其中包含相同的内部列表。既然你要改变内部列表,你也需要一个副本。在

最简单的方法是使用copy模块:

import copy
def moveDown(xPosition, yPosition, puzzle):
    returnPuzzle = copy.deepcopy(puzzle)

相关问题 更多 >

    热门问题