python的复制,浅拷贝,深拷贝区别
复制:默认浅拷贝对象的引用,原始改变,复制后的也会改变
>>> #复制
>>> alist=[7,8,9,["a","b"]]
>>> b=alist
>>> print(b)
[7, 8, 9, ['a', 'b']]
>>> alist.append(10)
>>> print(alist,b)
[7, 8, 9, ['a', 'b'], 10] [7, 8, 9, ['a', 'b'], 10]
浅拷贝:没有拷贝子对象,子对象只是引用,所以子对象改变,复制后的也会改变
>>> import copy
>>> c=copy.copy(alist)
>>> print(c)
[7, 8, 9, ['a', 'b'], 10]
>>> print(alist)
[7, 8, 9, ['a', 'b'], 10]
>>> alist.append(11)
>>> print(alist,c)
[7, 8, 9, ['a', 'b'], 10, 11] [7, 8, 9, ['a', 'b'], 10]
>>> alist[3].append("c")
>>> print(alist,c)
[7, 8, 9, ['a', 'b', 'c'], 10, 11] [7, 8, 9, ['a', 'b', 'c'], 10]
深拷贝:拷贝对象所有,原对象改变不会改变复制后的对象
>>> d=copy.deepcopy(alist)
>>> print(d)
[7, 8, 9, ['a', 'b', 'c'], 10, 11]
>>> alist[3].append("d")
>>> print(alist,d)
[7, 8, 9, ['a', 'b', 'c', 'd'], 10, 11] [7, 8, 9, ['a', 'b', 'c'], 10, 11]
>>> alist.append(12)
>>> print(alist,d)
[7, 8, 9, ['a', 'b', 'c', 'd'], 10, 11, 12] [7, 8, 9, ['a', 'b', 'c'], 10, 11]