使用y = x[:]
而不是y = x
。 y = x
表示y
和x
現在都指向同一個對象。
看看這個例子:
>>> 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()
函數,它使對象的非淺層副本。
謝謝。有用。你能解釋一下發生了什麼嗎?有什麼區別? –
@ lostboy_19我在答案中添加了解釋。 –
y = list(x)更容易理解與y = x相同的語法[:] –