Python copy模块
python中的赋值一般是传递对象的引用,修改一个对象,会导致其他对象也受到改变
python的copy模块提供了拷贝的函数,可以进行浅拷贝和深拷贝
copy模块提供了两个函数:
copy.copy(x) 返回x的浅拷贝,只拷贝x对象,不拷贝x内部的子对象
copy.deepcopy(x) 返回x的深拷贝,拷贝x对象及其子对象
下面看段代码就知道区别在哪了:
import copy sublist = ['a', 'b', 'c'] mylist = list(range(6)) mylist.append(sublist) mylist1 = copy.copy(mylist) mylist2 = copy.deepcopy(mylist) print('original ') print('mylist ', mylist) print('mylist1', mylist1) print('mylist2', mylist2) mylist.append(6) print("\nmylist append 6") print('mylist ', mylist) print('mylist1', mylist1) print('mylist2', mylist2) sublist.append('d') print("\nsublist append 'd'") print('mylist ', mylist) print('mylist1', mylist1) print('mylist2', mylist2)
输出的结果为:
original mylist [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']] mylist1 [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']] mylist2 [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']] mylist append 6 mylist [0, 1, 2, 3, 4, 5, ['a', 'b', 'c'], 6] mylist1 [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']] mylist2 [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']] #可见mylist1,mylist2都是拷贝,修改原来的list,不会影响拷贝出来的list sublist append 'd' mylist [0, 1, 2, 3, 4, 5, ['a', 'b', 'c', 'd'], 6] mylist1 [0, 1, 2, 3, 4, 5, ['a', 'b', 'c', 'd']] mylist2 [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']] #可见浅拷贝和深拷贝是有区别的,浅拷贝只是拷贝了list中子对象的引用,深拷贝拷贝了所有的子对象