复制的变量会改变原变量吗?

83 投票
3 回答
144227 浏览
提问于 2025-04-17 06:17

我在Python中遇到了一个简单但非常奇怪的问题。

def estExt(matriz,erro):
    # (1) Determinar o vector X das soluções
    print ("Matrix after:");
    print(matriz);

    aux=matriz;
    x=solucoes(aux); # IF aux is a copy of matrix, why the matrix is changed??

    print ("Matrix before: ");
    print(matriz)

...

如你所见,矩阵 matriz 发生了变化,尽管是 aux 被函数 solucoes() 修改。

修改前的矩阵:
[[7, 8, 9, 24], [8, 9, 10, 27], [9, 10, 8, 27]]

修改后的矩阵:
[[7, 8, 9, 24], [0.0, -0.14285714285714235, -0.2857142857142847, -0.42857142857142705], [0.0, 0.0, -3.0, -3.0000000000000018]]

3 个回答

7

aux 其实并不是 matrix 的一个副本,它只是一个不同的名字,用来指代同一个对象。

如果你想要真正的复制你的对象,可以使用 copy 模块

29

使用 copy 模块

aux = copy.deepcopy(matriz) # there is copy.copy too for shallow copying

小补充:不需要使用分号。

128

这一行

aux=matriz;

并不是在复制matriz,而只是创建了一个新的引用,叫做aux,指向matriz。你可能想要的是

aux=matriz[:]

这样做会复制matriz,前提是matriz是一个简单的数据结构。如果它比较复杂,你可能需要使用copy.deepcopy

aux = copy.deepcopy(matriz)

顺便提一下,你在每条语句后面不需要加分号,Python并不把它们当作结束符。

撰写回答