python直接赋值,浅拷贝和深拷贝

时间:2022-08-08 19:48:39

1.对于简单list结构

直接赋值只是简单的引用指向同一对象

而浅拷贝和深拷贝会指向不同的对象(简单结果浅拷贝和深拷贝的作用一样)

import copy

a = [1,2,3,4,5]
b = a
c = a.copy()
d = copy.deepcopy(a)
print(a,b,c,d)

# [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]

a.append(6)
print(a,b,c,d)

# [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]

 

2.对于复杂的结构

https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html