python基础深浅拷贝

发布于 2021-04-17 05:44 ,所属分类:知识学习综合资讯


目录

赋值运算

浅拷贝

深拷贝




详解

不可变的数据类型:缓存机制

可变的数据类型:深浅拷贝


(点击查看大图)



赋值运算

对于赋值运算来说,两个变量指向的是同一个内存地址,所以他们是完全一样的,任何一个变量对列表进行改变,剩下那个变量再使用列表的时候,这个列表就是发生改变之后的列表。



l1 = [1, 2, 3, ['pamela', 'apple']]l2 = l1
print(l1 is l2) # True
l1[0] = 111print(l1) # [111, 2, 3, ['pamela', 'apple']]print(l2) # [111, 2, 3, ['pamela', 'apple']]
l2[3][0] = 'abc'print(l1) # [111, 2, 3, ['abc', 'apple']]print(l2) # [111, 2, 3, ['abc', 'apple']]

(左右滑动查看完整代码)




浅拷贝

对于浅拷贝(copy)来说,只是在内存中新开辟了一个空间存放这个copy的列表(字典),但是新列表(字典)中的元素与原列表(字典)中的元素是公用的。(嵌套的可变的数据类型是同一个)



import copyl1 = [1, 'abc', True, (1, 2, 3), [22, 33], {'name': 'pamela', 'numbers': [123, 456, 789]}]l2 = l1.copy() # l2 = copy.copy(l1)  # 与上一行代码一样,都是浅拷贝 print(l1 is l2)  # Falseprint(l1[0] is l2[0])  # Trueprint(l1[1] is l2[1])  # Trueprint(l1[2] is l2[2])  # Trueprint(l1[3] is l2[3])  # Trueprint(l1[-2] is l2[-2])  # Trueprint(l1[-1] is l2[-1])  # Trueprint(l1[-1]['name'] is l2[-1]['name'])  # Trueprint(l1[-1]['numbers'] is l2[-1]['numbers'])  # Trueprint(l1[-1]['numbers'][1] is l2[-1]['numbers'][1])  # True

(左右滑动查看完整代码)



l1 = [1, 2, 3, ['pamela', 123]]l2 = l1[::] # 浅拷贝print(l1 is l2) # False

(左右滑动查看完整代码)




深拷贝

对于深拷贝(deepcopy)来说,列表(字典)是在内存中重新创建的,列表(字典)中可变的数据类型是重新创建的,列表(字典)中不可变的数据类型是公用的。(嵌套的可变的数据类型不是同一个)



import copyl1 = [1, 'abc', True, (1, 2, 3), [22, 33], {'name': 'pamela', 'numbers': [123, 456, 789]}]l2 = copy.deepcopy(l1)
print(l1 is l2) # Falseprint(l1[0] is l2[0]) # Trueprint(l1[1] is l2[1]) # Trueprint(l1[2] is l2[2]) # Trueprint(l1[3] is l2[3]) # Trueprint(l1[-2] is l2[-2]) # Falseprint(l1[-1] is l2[-1]) # Falseprint(l1[-1]['name'] is l2[-1]['name']) # Trueprint(l1[-1]['numbers'] is l2[-1]['numbers']) # Falseprint(l1[-1]['numbers'][1] is l2[-1]['numbers'][1]) # True

(左右滑动查看完整代码)




相关资源