参考python官方文档copy — 浅层 (shallow) 和深层 (deep) 复制操作,收藏一下。 浅层与深层复制的区别仅与复合对象(即包含列表或类的实例等其他对象的对象)相关: 浅层复制 构造一个新的复合对象,然后(在尽可能的范围内)将原始对象中找到的对象的 引用 插入其中。 深层复制 构造一个新的复合对象,然后,递归地将在原始对象里找到的对象的 副本 插入其中。
代码测试
一些代码测试 以列表为例,若直接b = a ,则相当于引用,对b操作等同于对a操作。 浅拷贝: b = a[:] 或b = copy.copy(a) 深拷贝: b = copy.deepcopy(a)
浅拷贝
x = [1, 2]
y = [3, 4]
a = [x, y]
print(a)
b = a[:]
print(b)
b[0] = 'abc'
print(b)
print(a)
[[1, 2], [3, 4]] [[1, 2], [3, 4]] [‘abc’, [3, 4]] [[1, 2], [3, 4]]
x = [1, 2]
y = [3, 4]
a = [x, y]
print(a)
b = a[:]
print(b)
b[0][0] = 'abc'
print(b)
print(a)
[[1, 2], [3, 4]] [[1, 2], [3, 4]] [[‘abc’, 2], [3, 4]] [[‘abc’, 2], [3, 4]]
import copy
x = [1, 2]
y = [3, 4]
a = [x, y]
print(a)
b = copy.copy(a)
print(b)
b[0] = 'abc'
print(b)
print(a)
[[1, 2], [3, 4]] [[1, 2], [3, 4]] [‘abc’, [3, 4]] [[1, 2], [3, 4]]
import copy
x = [1, 2]
y = [3, 4]
a = [x, y]
print(a)
b = copy.copy(a)
print(b)
b[0][0] = 'abc'
print(b)
print(a)
[[1, 2], [3, 4]] [[1, 2], [3, 4]] [[‘abc’, 2], [3, 4]] [[‘abc’, 2], [3, 4]]
可见在列表中b = a[:] 与b = copy.copy(a) 效果一致。
深拷贝
import copy
x = [1, 2]
y = [3, 4]
a = [x, y]
print(a)
b = copy.deepcopy(a)
print(b)
b[0] = 'abc'
print(b)
print(a)
[[1, 2], [3, 4]] [[1, 2], [3, 4]] [‘abc’, [3, 4]] [[1, 2], [3, 4]]
import copy
x = [1, 2]
y = [3, 4]
a = [x, y]
print(a)
b = copy.deepcopy(a)
print(b)
b[0][0] = 'abc'
print(b)
print(a)
[[1, 2], [3, 4]] [[1, 2], [3, 4]] [[‘abc’, 2], [3, 4]] [[1, 2], [3, 4]]
|