Python深淺copy

深copy和淺copy


深copy:不僅copy變量的指針,還copy指針指向的數據

這裏需要提到一個新名詞,指針:變量和內存中數據的一種引用關係。變量通過指針對應到內存中的數據
Python深淺copy

在列表、元組、字典、集合中可以使用深copy

list=[1,2,3];

copy的作用是將列表拷貝出一份

newlist=list.copy();
>>>print(list);
[1,2,3]
>>>print(newlist);
[1,2,3]

如果修改newlist中的某一個元素,不會影響到list列表中本來的的元素(深copy)

>>>newlist[2]='hehe';
>>>print(list)
[1,2,3]
>>>print(newlist)
[1,2,hehe]

淺copy:只copy了指針(一份內存的引用),而在內存中保存的數據,還是僅僅只有一份

Python深淺copy
在列表、元組、字典出現copy操作的時候會發生淺copy

>>>lists=[[1,2,3],3,4];
>>>newlists=lists.copy();
>>>print(newlists)
[[1,2,3],3,4]

改變newlists中元素的時候,如果修改,那麼會影響到lists

>>>newlists[0][2]='hiahia';
>>>print(lists)
>>>[[1, 2, 'hiahia'], 3, 4]
>>>print(newlists)
>>>[[1, 2, 'hiahia'], 3, 4]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章