深浅拷贝
1 a = [[1,2],2,3] 2 b = a.copy() 3 b[0] = 5 4 print(b) 5 print(a) 6 输出: 7 [5, 2, 3] 8 [[1, 2], 2, 3]
b = a[:] # 相当于b = a.copy()
查看变量id 例如:
1 a = 1 2 print(id(a),a) 3 b = a 4 print(id(b),b) 5 a = 2 6 print(id(a),a) 7 输出: 8 10914496 1 9 10914496 1 10 10914528 2
b = a 表示b获得a整体的地址,若给a整体赋值,那么a就会重新开辟一个内存空间 例子:
1 a = [[1,2,3],4,5] 2 print(id(a),a) 3 b = a 4 print(id(b),b) 5 a[2]=9 6 print(id(a),a) 7 print(id(b),b) 8 输出: 9 139798308770632 [[1, 2, 3], 4, 5] 10 139798308770632 [[1, 2, 3], 4, 5] 11 139798308770632 [[1, 2, 3], 4, 9] 12 139798308770632 [[1, 2, 3], 4, 9]
copy() 函数 实例 例如:
1 a = [[1,2,3],4,5,6] 2 b = a.copy() 3 print(id(a)) 4 print(id(b)) 5 a[2]=9 6 print(a,b) 7 a[0][0] = 0 8 print(a,b) 9 输出: 10 140671481131848 11 140671481132104 12 [[1, 2, 3], 4, 9, 6] [[1, 2, 3], 4, 5, 6] 13 [[0, 2, 3], 4, 9, 6] [[0, 2, 3], 4, 5, 6]
浅拷贝应用: 例子:
1 husband = ['小胖',123,[15000,9000]] 2 wife = husband.copy() 3 wife[0] = '小胖的老婆' 4 wife[1] = 456 5 husband[2][1] -= 3000 6 print(wife) 7 输出: 8 ['小胖的老婆', 456, [15000, 6000]]
import copy 里面的copy.copy() 相当于浅拷贝a.copy(),shallow浅,表面
deepcopy(a) 深拷贝,复制所有。所有的id地址 例子
1 import copy 2 husband = ['小胖',123,[15000,9000]] 3 wife = husband.copy() 4 xiaosan = copy.deepcopy(husband) 5 xiaosan[0] = '小三' 6 xiaosan[1] = 333 7 wife[0] = '小胖的老婆' 8 wife[1] = 456 9 husband[2][1] -= 3000 10 print(wife) 11 print(xiaosan) 12 输出: 13 ['小胖的老婆', 456, [15000, 6000]] 14 ['小三', 333, [15000, 9000]]
不会改变其他的