2012-06-23 35 views
0

我正在加載變量'x'中的二維文件「data.imputation」。變量'y''x'的副本。我從'y'(y是2D)彈出第一個數組。爲什麼變化反映在x? (從'x'第一陣列也被彈出)在python中複製數組並操作其中一個

ip = open('data.meanimputation','r') 
x = pickle.load(ip) 
y = x 
y.pop(0) 

在開始時,len(x) == len(y)。即使在y.pop(0),len(x) == len(y)之後。這是爲什麼?我該如何避免它?

回答

2

使用y = x[:]而不是y = xy = x表示yx現在都指向同一個對象。

看看這個例子:

>>> x=[1,2,3,4] 
>>> y=x 
>>> y is x 
True   # it means both y and x are just references to a same object [1,2,3,4], so changing either of y or x will affect [1,2,3,4] 
>>> y=x[:]  # this makes a copy of x and assigns that copy to y, 
>>> y is x  # y & x now point to different object, so changing one will not affect the other. 
False 

如果x是一個列表,列表的名單,然後[:]是沒有用的:

>>> x= [[1,2],[4,5]] 
>>> y=x[:] #it makes a shallow copy,i.e if the objects inside it are mutable then it just copies their reference to the y 
>>> y is x 
False   # now though y and x are not same object but the object contained in them are same 
>>> y[0].append(99) 
>>> x 
[[1, 2, 99], [4, 5]] 
>>> y 
[[1, 2, 99], [4, 5]] 
>>> y[0] is x[0] 
True #see both point to the same object 

在這種情況下,你應該使用copy模塊的deepcopy()函數,它使對象的非淺層副本。

+0

謝謝。有用。你能解釋一下發生了什麼嗎?有什麼區別? –

+0

@ lostboy_19我在答案中添加了解釋。 –

+0

y = list(x)更容易理解與y = x相同的語法[:] –

1

y = x不會複製任何內容。它將名稱y綁定到x已提及的相同對象。分配給裸名稱從不復制Python中的任何內容。

如果你想複製一個對象,你需要明確地複製它,使用任何可用於你要複製的對象的方法。你不會說什麼樣的對象x是,所以沒有辦法說出你可以如何複製它,但copy模塊提供了一些適用於多種類型的函數。另見this answer

+0

因此y = x.copy()應該工作嗎? –

+0

這取決於'x'是什麼類型的對象。如果'x'提供了這樣一種方法(比如Python字典),它就會工作。你也可以嘗試'import copy'然後'y = copy.copy(x)'。但是,如果將x設置爲以這種方式複製,那也只能起作用。 Python中沒有通用的方法來「複製任何東西」;你需要知道你正在複製什麼樣的東西,並知道如何複製它。 – BrenBarn

+0

x是一個列表。例如x = [[1,2],[4,5]] –

相關問題