Python列出相互分配的值

Python列出相互分配的值,python,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)

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

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语句说它们不是指向内存中同一点的指针,对吗

您只是创建嵌套列表的浅表副本,因此对它们进行变异仍然会影响两个矩阵。您可能需要使用
copy.deepcopy

您只是创建嵌套列表的浅拷贝,因此对它们进行变异仍然会影响两个矩阵。您可能需要使用
copy.deepcopy

is关键字检查两个变量的
id
。id对应于内存中变量的位置(在CPython实现中)。正如文档中所说:@segfolt:这正是OP想要的<如果它们是同一个对象,则“代码>a”是“b”是“真”。@Blender:是。因为OP的最后一个问题,
is
关键字检查两个变量的
id
。id对应于内存中变量的位置(在CPython实现中)。正如文档中所说:@segfolt:这正是OP想要的<如果它们是同一个对象,则“代码>a”是“b”是“真”。@Blender:是。因为OP的最后一个问题,这只是一个精度。你是对的。非常感谢。你说得对。非常感谢。