Python列表等价

时间:2015-11-23 00:12:25

标签: python list

当我更改列表的值时,其他列表也会更改。我不明白他们为什么这样做。

def successors(state):

    stateup=state[:]
    statedown=state[:]
    stateright=state[:]
    stateleft=state[:]


    for i in range(len(state)):
        for j in range(len(state)):
            if state[i][j]==0:
                x=i
                y=j

    stateup[x][y]=stateup[x+1][y]
    stateup[x+1][y]=0
    statedown[x][y]=statedown[x-1][y]
    statedown[x-1][y]=0
    stateright[x][y]=stateright[x][y-1]
    stateright[x][y-1]=0
    stateleft[x][y]=stateleft[x][y+1]
    stateleft[x][y+1]=0
    if x==0:
        if y==0:
            return [stateleft,stateup]
        elif y==len(state)-1:
            return [stateright,stateup]
        else:
            return [stateright,stateleft,stateup]
    elif x==len(state)-1:
        if y==0:
            return [stateleft,statedown]
        elif y==len(state)-1:
            return [stateright,statedown]
        else:
            return [stateright,stateleft,statedown]
    else:
        return [stateright,stateleft,statedown,stateup]

print successors([[1,2,3,4],[5,6,0,8],[9,10,11,12],[13,14,15,16]])

1 个答案:

答案 0 :(得分:2)

您定义的变量stateup statedown ...都是state的浅层副本。因为您使用了[:]来制作列表的浅表副本。所以更改其中一个会改变所有这些。您需要使用copy.deepcopy(...)对其进行深层复制。 如需完整解释,请阅读此问题 Deep copy a list in Python
和这篇文章 http://www.python-course.eu/deep_copy.php