尽管有副本,全球名单仍在不

时间:2014-10-01 12:00:14

标签: python list copy

我很难理解为什么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

2 个答案:

答案 0 :(得分:3)

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

创建嵌套列表的副本:

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

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

这会创建每个嵌套列表的浅表副本。

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

答案 1 :(得分:3)

tempqueue = lst[:]制作浅色副本,而不是深层副本。这意味着您获得了一个新的容器列表,但引用了完全相同的内容。由于内容本身就是列表,因此您将获得对可变对象的引用。如果您在lsttempqueue中改变这些列表,那么另一个也会受到影响。

如果您想要列表清单的深层副本,可以使用

tempqueue = [[x for x in item] for item in lst]

tempqueue = [list(item) for item in lst]

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

或者,对于更深层次的嵌套结构,您可以使用

tempqueue = copy.deepcopy(lst)

example here显示使用浅版和深版之间的区别。