一、浅拷贝
1、直接复制
两个列表是等价的,修改其中任何一个列表都会影响到另一个列表。
old = [1,[1,2,3],3]
print('原old=',old)
new = old
new[0] = 3
new[1][0] =3
new[2]=4
print('old=',old)
print('new=',new)
原old= [1, [1, 2, 3], 3]
old= [3, [3, 2, 3], 4]
new= [3, [3, 2, 3], 4]
2、copy()
第一层实现了深拷贝,但对于其内嵌套的List,仍然是浅拷贝。
因为嵌套的List保存的是地址,复制过去的时候是把地址复制过去了,嵌套的List在内存中指向的还是同一个
old = [1,[1,2,3],3]
print('原old=',old)
new = old.copy()
new[0] = 3
new[1][0] =3
new[2]=4
print('old=',old)
print('new=',new)
原old= [1, [1, 2, 3], 3]
old= [1, [3, 2, 3], 3]
new= [3, [3, 2, 3], 4]
3、列表生成式
只对第一层实现深拷贝
old = [1,[1,2,3],3]
print('原old=',old)
new = [i for i in old]
new[0] = 3
new[1][0] =3
new[2]=4
print('old=',old)
print('new=',new)
原old= [1, [1, 2, 3], 3]
old= [1, [3, 2, 3], 3]
new= [3, [3, 2, 3], 4]
4、[:]切片
只对第一层实现深拷贝
old = [1,[1,2,3],3]
print('原old=',old)
new = old[:]
new[0] = 3
new[1][0] =3
new[2]=4
print('old=',old)
print('new=',new)
原old= [1, [1, 2, 3], 3]
old= [1, [3, 2, 3], 3]
new= [3, [3, 2, 3], 4]
二、深拷贝deepcopy()
import copy
old = [1,[1,2,3],3]
print('原old=',old)
new = copy.deepcopy(old)
new[0] = 3
new[1][0] =3
new[2]=4
print('old=',old)
print('new=',new)
原old= [1, [1, 2, 3], 3]
old= [1, [1, 2, 3], 3]
new= [3, [3, 2, 3], 4]
参考:
https://blog.csdn.net/weixin_49899130/article/details/129380610?spm=1001.2014.3001.5506