赋值
相当于同一块内存地址贴上了不同的标签.
比如 a=10,b=a;a 和 b 就是'10'所在内存地址的不同标签而已.
浅拷贝 简单理解就是以下规则
浅拷贝的时候只拷贝第一层元素.
浅拷贝在修改第一层元素 (不可变数据类型) 的时候, 拷贝出来的新列表不进行改变.
浅拷贝在替换第一层元素 (可变数据类型) 的时候, 拷贝出来的新列表不进行改变.
浅拷贝在修改第一层元素中的元素 (第二层) 的时候, 拷贝出来的新列表进行改变.
下面给出一些例子:
- lst = [1,2,3,[5,6,7]]
- lst1 = lst.copy()
- lst1[-1].append(8)
- print(lst)
- print(lst1)
输出 [1, 2, 3, [5, 6, 7, 8]]
- [1, 2, 3, [5, 6, 7, 8]]
- lst = [1,2,3,[5,6,7]]
- lst1 = lst.copy()
- lst[3] = 567
- print(lst1)
- print(lst)
输出 [1, 2, 3, [5, 6, 7]]
- [1, 2, 3, 567]
- lst = [1,2,3,4,[5,6,7,[8,9]]]
- lst1 = lst.copy() # [1,2,3,4,[5,6,7,[8,9]],10]
- lst1.append(10)
- print(lst)
- print(lst1)
输出 [1, 2, 3, 4, [5, 6, 7, [8, 9]]]
- [1, 2, 3, 4, [5, 6, 7, [8, 9]], 10]
- lst = [1,2,3,4,[5,6,7,[8,9,]]]
- lst1 = lst.copy()
- lst[-1][-1] = 56
- print(lst)
- print(lst1)
输出 [1, 2, 3, 4, [5, 6, 7, 56]]
- [1, 2, 3, 4, [5, 6, 7, 56]]
- lst = [[1,2,],90,6,7,[5,6]]
- lst1 = lst.copy()
- lst1[-1] = 8
- print(lst)
- print(lst1)
输出 [[1, 2], 90, 6, 7, [5, 6]]
- [[1, 2], 90, 6, 7, 8]
- dic = {
- "jerry":[1,2,3,[5,6]]
- }
- dic1 = dic.copy()
- dic["jerry"][0] = "56"
- print(dic)
- print(dic1)
输出 {'jerry': ['56', 2, 3, [5, 6]]}
{'jerry': ['56', 2, 3, [5, 6]]}
深拷贝
深拷贝开辟一个容器空间(列表), 不可变数据公用, 可变数据数据类型(再次开辟一个新的空间)
- import copy
- lst = [1,2,3,[5,6,7]]
- lst1 = copy.deepcopy(lst) # 深拷贝
- lst[-1].append(8)
- print(lst)
- print(lst1)
- # 输出 [1, 2, 3, [5, 6, 7, 8]]
- [1, 2, 3, [5, 6, 7]]
- lst = [1,2,3,[5,6,7,[8,10,9]]]
- import copy
- ls1 = copy.deepcopy(lst)
- print(id(lst[-1][-1]))
- print(id(lst1[-1][-1]))
- # 输出 1604930721864
- 1604932258952
来源: http://www.bubuko.com/infodetail-3494866.html