python的copy.copy()和copy.deepcopy()方法
阿新 • • 發佈:2019-02-19
python中copy.copy()是淺拷貝,只拷貝父物件,不會拷貝物件的內部的子物件。copy.deepcopy()是深拷貝,會拷貝物件及其子物件。
import copy aList = ['1',2,'a',['b','c']] bList = aList#將aList賦給bList cList = copy.copy(aList)#淺拷貝 dList = copy.deepcopy(aList)#深拷貝 aList.append('test')#在aList末尾新增'test' aList[3].append('list')#在aList中['b','c']的末尾新增'list' print 'aList:%s'% aList print 'bList:%s'% bList print 'cList:%s'% cList print 'dList:%s'% dList
結果:
aList:['1', 2, 'a', ['b', 'c', 'list'], 'test']
bList:['1', 2, 'a', ['b', 'c', 'list'], 'test']
cList:['1', 2, 'a', ['b', 'c', 'list']]
dList:['1', 2, 'a', ['b', 'c']]