python的copy.copy()和copy.deepcopy()方法

时间:2021-09-05 19:50:27

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']]