Python 列表浅拷贝与深拷贝
浅拷贝 shallow copy 和深拷贝 deep copy
list.copy() 浅拷贝:复制此列表(只复制一层,不会复制深层对象) 等同于 L[:]
举例:
浅拷贝:
a = [1.1, 2.2] # a = [1.1, 2.2]
b = [1, 2, a] # b = [1, 2, [1.1, 2.2]]
c = b.copy() # c = [1, 2, [1.1, 2,2]]
a[0] = 1.123
b = [1, 2, [1.123, 2.2]]
c = [1, 2, [1.123, 2.2]]
内存中的指向是这样的,如下图:
深拷贝:
注:使用deepcoyp前需要导入copy模块。
Import copy # 导入copy模块
a = [1.1, 2.2] # a = [1.1, 2.2]
b = [1, 2, a] # b = [1, 2, [1.1, 2.2]]
c = b.deepcopy() # c = [1, 2, [1.1, 2,2]]
a[0] = 1.123
b = [1, 2, [1.123, 2.2]]
c = [1, 2, [1.1, 2.2]]
内存中的指向是这样的,如下图: