python--深浅拷贝
例子:
a = [21,56,['liangchen','zhang']]
1、b = a
- b指向的列表地址就是a指向的列表地址
- b列表中元素的值改变,a列表中的元素的值也跟着改变
a = [21,56,['liangchen','zhang']] b = a b[0] = 22 print(id(a)) print(id(b)) print(a,b) 输出: 1342819623624 1342819623624 [22, 56, ['liangchen', 'zhang']] [22, 56, ['liangchen', 'zhang']]
2、浅拷贝:b = a.copy()
- b重新开辟了一个新的地址
- b列表中元素值的改变,a并不会变,因为两者并不是指向的同一地址,只是两者初始值元素相同而已
- 如果b列表中还有一层列表,那么改变第二层的列表的元素,则a对应的元素也会改变,因为第二层列表的地址和a中的第二层的列表的地址相同
a = [21,56,['liangchen','zhang']] b = a.copy() b[0] = 22 print(id(a)) print(id(b)) print(a,b) 输出: 2066816787144 2066817291720 [21, 56, ['liangchen', 'zhang']] [22, 56, ['liangchen', 'zhang']]
a = [21,56,['liangchen','zhang']] b = a.copy() b[2][1] = 'chen' print(id(a[2])) print(id(b[2])) print(a,b) 输出: 1897167741512 1897167741512 [21, 56, ['liangchen', 'chen']] [21, 56, ['liangchen', 'chen']]
3、深拷贝(导入:import copy):b = copy.deepcopy()
- b重新开辟了一个新的地址
- b的第二层列表也重新开辟了新的地址
- b列表中元素值的改变,a并不会变
- b嵌套的第二层列表中的元素改变,a也不会变
import copy a = [21,56,['liangchen','zhang']] b = copy.deepcopy(a) b[2][1] = 'chen' print(id(a),id(b)) print(id(a[2]),id(b[2])) print(a,b) 输出: 1706386976584 1706387605832 1706387465352 1706387605896 [21, 56, ['liangchen', 'zhang']] [21, 56, ['liangchen', 'chen']]