2011-11-14 36 views
15

我有一個非常奇怪的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]]

回答

31

aux=matriz; 

不使matriz副本,它只是創建一個新的參考matriz命名aux。你可能想要

aux=matriz[:] 

哪一個會複製,假設matriz是一個簡單的數據結構。如果是比較複雜的,你應該使用copy.deepcopy

aux = copy.deepcopy(matriz) 

順便說一句,你不需要分號每個語句後,Python不使用它們作爲EOL標誌。

+0

嗨,感謝您的回答=)但我有另一個考慮到這個事實的問題:如果b = 1和a = b,如果我們改變a = 3,則b在python中不會改變。爲什麼?謝謝=) –

+4

因爲你改變'a'指向一個不同的對象(整數'3'),但不改變'b',所以它仍然指向'1'。 – kindall

2

auxmatrix副本,它只是指相同對象的不同的名稱。使用copy module創建對象的實際副本。

9

使用copy模塊

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

次要之一:不需要分號。

+0

感謝您的回答=) –

+1

歡迎來到stackoverflow @AndréFreitas。通常在這裏,接受其中一個答案被認爲是一種良好的社區實踐(你認爲最好的一個,不一定是我的)。 – Shekhar