Python列表值彼此分配

时间:2013-04-17 23:55:36

标签: python

我在编写以下代码时遇到问题:

D = [
        [0,3,8,999,-4],
        [999,0,999,1,7],
        [999,4,0,999,999],
        [2,999,-5,0,999],
        [999,999,999,6,0]
    ]

def FloydWarshall (W):
    matrices = [W[:]]
    pred = [W[:]]

    print (matrices is pred)
    print (pred is matrices)
    print (pred is W)
    print (matrices is W)

    for i in range(0,len(pred[0])):
        for j in range(len(pred[0][i])):

            if pred[0][i][j] != 999 and pred[0][i][j] != 0:
                pred[0][i][j] = i +1
            else:
                pred[0][i][j] = False 

    return (matrices,pred)
FloydWarshall(D)

返回的值是完全相同的矩阵,为什么会这样? print语句说它们不是指向内存中相同位置的指针,对吗?

1 个答案:

答案 0 :(得分:5)

您只是对嵌套列表进行浅层复制,因此对它们进行改变仍会影响两个矩阵。您可能想要使用copy.deepcopy