2.深拷贝和浅拷贝
2020-12-10 本文已影响0人
Stone_説
目录
1.浅拷贝
2.深拷贝
1.浅拷贝
1.1 "="拷贝
list_dest = list_src
完全同步,引用指向同一块内存地址
>>> lst1 = [1,[1,2,3],3]
>>> lst2 = lst1
>>> lst2
[1, [1, 2, 3], 3]
>>> lst1
[1, [1, 2, 3], 3]
>>> lst1[1][1] = 100
>>> lst1
[1, [1, 100, 3], 3]
>>> lst2
[1, [1, 100, 3], 3]
>>> lst1 == lst2
True
>>> lst1 is lst2
True
>>> id(lst1)
140057086705472
>>> id(lst2)
140057086705472
1.2 "[:]"方式复制
list_dest = list_src[:]
非引用列表复制,如果改变,遇到引用类型,复制一个应用而已
>>> lst1 = [1,[1,2,3],3]
>>> lst2 = lst1[:]
>>> lst2
[1, [1, 2, 3], 3]
>>> lst1 == lst2
True
>>> lst1 == lst2 ,lst1 is lst2
(True, False)
>>> id(lst1),id(lst2)
(139997400596416, 139997400633472)
>>> id(lst1[1]),id(lst2[1])
(139997400596352, 139997400596352)
>>> lst1[0] = 5
>>> lst1,lst2
([5, [1, 2, 3], 3], [1, [1, 2, 3], 3])
>>> lst1[1][1] = 100
>>> lst1,lst2
([5, [1, 100, 3], 3], [1, [1, 100, 3], 3])
1.3 copy方法调用
list_dest = list_src.copy(),和1.2的方式一样
同上,也是一种浅拷贝
>>> lst1 = [1,[1,2,3],3]
>>> lst2 = lst1.copy()
>>> id(lst1[1]),id(lst2[1])
(139997400634496, 139997400634496)
>>> lst1[1][1] = 100
>>> lst1
[1, [1, 100, 3], 3]
>>> lst2
[1, [1, 100, 3], 3]
2.深拷贝
list_dest = copy.deepcopy(list_src),copy模块中的deepcopy方法
二者完全不同,完全指向不同内存地址
>>> import copy
>>> lst1 = [1,[1,2,3],3]
>>> lst2 = copy.deepcopy(lst1)
>>> id(lst1[1]),id(lst2[1])
(139997400635456, 139997400808192)
>>> id(lst1),id(lst2)
(139997400808128, 139997400634432)
>>> lst1[1][1] = 100
>>> lst1,lst2
([1, [1, 100, 3], 3], [1, [1, 2, 3], 3])
>>> lst1 == lst2,lst1 is lst2
(False, False)