Skip to main content
 首页 » 编程设计

python之全局列表不断变化,尽管复制

2025年05月04日15mq0036

我很难理解为什么 expqueue 不断变化到状态的多次迭代, 我已经尝试了从 [:] 到深层复制的所有内容。有人可以解释什么是错的吗? 该代码适用于 8 人益智游戏,如果我能得到所有不同游戏的运行列表 组合 我确定我可以自己完成这个,是的,这是家庭作业。

import copy 
init = [[2,0,3], [1,5,6],[4,7,8]] 
goal = [[1,2,3], [4,5,6],[7,8,0]] 
expqueue = [] 
tempqueue = [] 
depth = 0 
 
def myappend(lst1, lst2): 
    new = list(lst1) 
    new2 = list(lst2) 
    new.append(new2) 
    global expqueue 
    expqueue = new 
 
def makeState(state): 
for x in range(0,3): 
    for i in range(0,3): 
        print state[x][i], 
    print "\n" 
 
 
def locate(state): 
    for x in range(0,3): 
        for y in range(0,3): 
            if state[x][y] == 0: 
                return [x, y] 
 
def moveU(state): 
    location = locate(state) 
    x = location[0] 
    y = location[1] 
    s = x-1 
    if x>0: 
        swap = state[x][y] 
        state[x][y] = state[s][y] 
        state[s][y] = swap 
        myappend(expqueue, state) 
 
def moveL(state): 
    location = locate(state) 
    x = location[0] 
    y = location[1] 
    s = y-1 
    if y>0: 
        swap = state[x][y] 
        state[x][y] = state[x][s] 
        state[x][s] = swap 
        myappend(expqueue, state) 
 
def moveR(state): 
    location = locate(state) 
    x = location[0] 
    y = location[1] 
    s = y+1 
    if y<2: 
        swap = state[x][y] 
        state[x][y] = state[x][s] 
        state[x][s] = swap 
        myappend(expqueue, state) 
 
def moveD(state): 
    location = locate(state) 
    x = location[0] 
    y = location[1] 
    s = x+1 
    if x<2: 
        swap = state[x][y] 
        state[x][y] = state[s][y] 
        state[s][y] = swap 
        myappend(expqueue, state) 
 
def expand(lst): 
    tempqueue = lst[:] 
    while tempqueue != []: 
        state = tempqueue[0] 
        current = state[:] 
        moveU(current) 
        moveL(current) 
        moveR(current) 
        moveD(current) 
        del tempqueue[0] 
    return expqueue 
 
def solve(queue, initial, solution, level): 
    length = len(queue) 
    for x in range(length): 
        if queue[x] == solution: 
            return "This works!" 
    return solve(expand(queue), initial, solution, level+1) 
 
print solve([init], init, goal, 0) 

从那以后,我在初始切片上添加了深度复制,并且我注意到复制后 ID 恢复原状。有谁知道为什么吗?

显然我没有足够的街头信誉来发布屏幕截图,所以这里有一个链接: Matching id's after copy

请您参考如下方法:

您正在更改嵌套 列表,但只复制了外部 列表; list(original) 或 original[:] 调用只会创建一个浅拷贝;新列表“继承”了对内容的引用,如果这些内容是可变的,那么您将在这两个地方看到这些内容的更改。

创建嵌套列表的副本:

new = [nested[:] for nested in lst1] 

和

tempqueue = [nested[:] for nested in lst] 

这会创建每个嵌套列表的浅拷贝。

或者使用 copy.deepcopy() function递归复制对象。