关于深拷贝浅拷贝的面试题

import copy
list1 = [1, 2, ['a', 'b'], ('c', 'd')]
list2 = list1
list3 = copy.copy(list1)  # 如果是可变类型,浅拷贝只拷贝外层,而深拷贝是完全拷贝
list4 = copy.deepcopy(list1)
list1.append(3)
tuple1 = (10, 10)
list1[2].append({100})
list1[3] = list1[3] + tuple1  # 元组与元组之间相加得到一个 新元组
dict1 = {}
dict1["1"] = 1111
list1[2].append(dict1)
print(list1)
print(list2)
print(list3)
print(list4)

运行结果:

[1, 2, ['a', 'b', {100}, {'1': 1111}], ('c', 'd', 10, 10), 3]
[1, 2, ['a', 'b', {100}, {'1': 1111}], ('c', 'd', 10, 10), 3]
[1, 2, ['a', 'b', {100}, {'1': 1111}], ('c', 'd')]
[1, 2, ['a', 'b'], ('c', 'd')]

猜你喜欢

转载自blog.csdn.net/weixin_44786231/article/details/89428220