简体   繁体   English

Python列表等效

[英]Python List Equivalence

When I change the value of the list, the other lists also be changed. 当我更改列表的值时,其他列表也将更改。 I don't understand why they do. 我不明白他们为什么这么做。

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]])

The variables stateup statedown ... you have defined are all shallow copies of state . 变量stateup statedown ...您已经定义都是浅拷贝state Because you have used [:] which makes a shallow copy of the list. 因为您使用了[:] ,所以它只是列表的浅表副本。 So changing one of them changes all of them. 因此,更改其中之一将更改所有这些。 You need to deep copy them Using copy.deepcopy(...) . 您需要使用copy.deepcopy(...)深度复制它们。 For full explanation read this question Deep copy a list in Python 有关此问题的完整说明,请深度阅读Python中的列表
and this article http://www.python-course.eu/deep_copy.php 和这篇文章http://www.python-course.eu/deep_copy.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM