简体   繁体   中英

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 . 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(...) . For full explanation read this question Deep copy a list in Python
and this article http://www.python-course.eu/deep_copy.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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