Shallow and Deep Copy

list1 = ['a','b','c','d']
list2 = list1  
list2[1] = 'x'
print(list2)
print(list1)
 # 输出:
['a', 'x', 'c', 'd']
['a', 'x', 'c', 'd']

上述情形,list1和list2指向同一个list object
这里写图片描述

可以用list的slice方法创造shallow copy:

list1 = ['a','b','c','d']  
list2 = list1[:]  
# copy shallow list structures with the slice operator 
# without having any of the side effects
list2[1] = 'x'
print(list2)
print(list1)
 # 输出:
['a', 'x', 'c', 'd']
['a', 'b', 'c', 'd']

shallow copy会遇见的问题:嵌套的列表还是共用的。

lst1 = ['a','b',['ab','ba']]
lst2 = lst1[:]

这里写图片描述

lst1 = ['a','b',['ab','ba']]
lst2 = lst1[:]
lst2[0] = 'c'
print(lst1)
# ['a', 'b', ['ab', 'ba']]
print(lst2)
# ['c', 'b', ['ab', 'ba']]

这里写图片描述

lst2[2][1] = 'd'
print(lst1)
# ['a', 'b', ['ab', 'd']]
print(lst2)
# ['c', 'b', ['ab', 'd']]

可以发现嵌套的列表还是共用的。

这里写图片描述

可以用deepcopy来解决这个问题:

from copy import deepcopy
lst1 = ['a','b',['ab','ba']]
lst2 = deepcopy(lst1)
lst1
# ['a', 'b', ['ab', 'ba']]
lst2
# ['a', 'b', ['ab', 'ba']]
id(lst1)
# 139716507600200
id(lst2)
# 139716507600904
id(lst1[0])
# 139716538182096
id(lst2[0])
# 139716538182096
id(lst2[2])  
# 139716507602632
id(lst1[2])
# 139716507615880
# 可以发现嵌套的列表地址是不同的

这里写图片描述

lst2[2][1] = "d"
lst2[0] = "c"
print(lst1)
# ['a', 'b', ['ab', 'ba']]
print(lst2)
# ['c', 'b', ['ab', 'd']]

这里写图片描述

Reference:
Shallow and Deep Copy

猜你喜欢

转载自blog.csdn.net/maverick_7/article/details/79198114