下面展示**
import copy
淺拷貝:copy.copy
深拷貝:copy.deepcopy
import copy
mylist =[0
,1,2
,["a",
"b",
"c"]
] # 原列表 original
myliste = mylist # 使用等號賦值 assignment using equal sign
mylists = copy.
copy
(mylist) # 淺拷貝 shallow copy
mylistd = copy.
deepcopy
(mylist)# 深拷貝 deep copy
print
("\n mylist:"
,mylist)
print
("myliste:"
,myliste)
print
("mylists:"
,mylists)
print
("mylistd:"
,mylistd)
print
("\n\n\n修改基本型別的元素後:"
)mylist[0]
=9print
(" mylist:"
,mylist)
print
("myliste:"
,myliste)
print
("mylists:"
,mylists)
print
("mylistd:"
,mylistd)
print
("\n\n\n修改引用型別的元素後:"
)mylist[3]
[2]=
"林麻子..."
print
(" mylist:"
,mylist)
print
("myliste:"
,myliste)
print
("mylists:"
,mylists)
print
("mylistd:"
,mylistd)
輸出結果:
mylist: [0, 1, 2, ['a', 'b', 'c']]
myliste: [0, 1, 2, ['a', 'b', 'c']]
mylists: [0, 1, 2, ['a', 'b', 'c']]
mylistd: [0, 1, 2, ['a', 'b', 'c']]
修改基本型別的元素後:
mylist: [9, 1, 2, ['a', 'b', 'c']]
myliste: [9, 1, 2, ['a', 'b', 'c']]
mylists: [0, 1, 2, ['a', 'b', 'c']]
mylistd: [0, 1, 2, ['a', 'b', 'c']]
修改引用型別的元素後:
mylist: [9, 1, 2, ['a', 'b', '林麻子...']]
myliste: [9, 1, 2, ['a', 'b', '林麻子...']]
mylists: [0, 1, 2, ['a', 'b', '林麻子...']]
mylistd: [0, 1, 2, ['a', 'b', 'c']]
------------------
(program exited with code: 0)
請按任意鍵繼續. . .
Python之深拷貝和淺拷貝
賦值,深拷貝和淺拷貝的區別?python中如何拷貝乙個物件?直接賦值 li1 li 只傳遞物件的引用,li1指向物件li的記憶體位址空間,因此,原有列表li改變,被賦值的li1也會做相應的改變.深拷貝 import copy,eg li3 copy.deepcopy li li和li3的記憶體位址不...
python 深拷貝 Python深拷貝和淺拷貝!
在python中,物件賦值實際上是物件的引用。當建立乙個物件,然後把它賦給另乙個變數的時候,python並沒有拷貝這個物件,而只是拷貝了這個物件的引用 一般有三種方法,alist 1,2,3,a b 1 直接賦值 b alist,預設淺拷貝傳遞物件的引用而已,原始列表改變,被賦值的b也會做相同的改變...
python高階之深拷貝和淺拷貝
a 18b 18id a 結果為4321867632 id b 結果為4321867632c 1 2,3 d 1 2,3 e c id c 結果為4372284616 id d 結果為4371531592 id e 結果為4372284616 這就是python裡面關於變數和引用的關係,如果我們通過...