1. 列表(list)
alist = [1, 2, 3] ## 初始化一個列表
blist = alist ## blist 引用 akist
clist = alist[:] ## clist 復制 alist
print("old list is :")
print "alist is : ", alist
print "blist is : ", blist
print "clist is : ", clist
alist[1] = 3
print("new list is :")
print "alist is : ", alist
print "blist is : ", blist
print "clist is : ", clist
結果如下所示:
(python_test) ? 20180723 python test.py
old list is :
alist is : [1, 2, 3]
blist is : [1, 2, 3]
clist is : [1, 2, 3]
new list is :
alist is : [1, 3, 3]
blist is : [1, 3, 3]
clist is : [1, 2, 3]
(python_test) ? 20180723
其變量與對象的變化如下圖所示
2. 字典(dict)
adict = {'name': 'zhaoxin'}
bdict = adict
cdict = adict.copy()
print("old dict is: ")
print "adict is : ", adict
print "bdict is : ", bdict
print "cdict is : ", cdict
adict['name'] = 'songzhen'
print("new dict is: ")
print "adict is : ", adict
print "bdict is : ", bdict
print "cdict is : ", cdict
結果如下所示:
(python_test) ? 20180723 python test2.py
old dict is:
adict is : {'name': 'zhaoxin'}
bdict is : {'name': 'zhaoxin'}
cdict is : {'name': 'zhaoxin'}
new dict is:
adict is : {'name': 'songzhen'}
bdict is : {'name': 'songzhen'}
cdict is : {'name': 'zhaoxin'}
(python_test) ? 20180723
3. 深度復制
無條件值的分片和字典的copy只能做頂層復制跺涤,如果需要一個深層嵌套的數(shù)據(jù)結構的完整的钦铁,完全獨立的復制才漆,則需要使用標準的copy模塊來處理。
如下例所示:
import copy
dict1 = {"name": 'zhaoxin'}
test1 = [1, 2, 3, [3, 4, dict1]]
test2 = test1[:] ## 頂層復制
test3 = copy.deepcopy(test1) ## 深度復制
print "old is : "
print "test1 is : ", test1
print "test2 is : ", test2
print "test3 is : ", test3
dict1["name"] = "songzhen"
test1[2] = 4
print "new is : "
print "test1 is : ", test1
print "test2 is : ", test2
print "test3 is : ", test3
結果如下所示
(python_test) ? 20180723 python test3.py
old is :
test1 is : [1, 2, 3, [3, 4, {'name': 'zhaoxin'}]]
test2 is : [1, 2, 3, [3, 4, {'name': 'zhaoxin'}]]
test3 is : [1, 2, 3, [3, 4, {'name': 'zhaoxin'}]]
new is :
test1 is : [1, 2, 4, [3, 4, {'name': 'songzhen'}]]
test2 is : [1, 2, 3, [3, 4, {'name': 'songzhen'}]]
test3 is : [1, 2, 3, [3, 4, {'name': 'zhaoxin'}]]
(python_test) ? 20180723