深浅拷贝
浅拷贝:
浅拷贝只拷贝一次,浅拷贝只拷贝指针。
import copy copy.copy() #浅拷贝 a1 = 123123 a2 = 123123 print(id(a1)) #查看内存地址 print(id(a2)) #22745648 #22745648 a3 = copy.copy(a1) print(id(a1)) print(id(a3)) #22745648 #内存地址相同 #22745648
深拷贝:
深拷贝拷贝多层,深拷贝可以重新申请空间并将数据复制过来
1 n1 = {'k1':'wu','k2':123,'k3':['alex',456]} 2 n2 = n1 3 print(id(n1)) #39035368 4 print(id(n2)) #39035368 5 n3 = copy.copy(n1) 6 n4 = copy.deepcopy(n1) 7 print(id(n1)) #39035368 8 print(id(n3)) #39295376 9 print(id(n4)) #39035608 10 print(id(n1['k3'])) #46733552 11 print(id(n3['k3'])) #46733552 12 print(id(n4['k3'])) #46731352 13 14 dic = { 15 "cpu":[80,], 16 "mem":[80,], 17 "disk":[80,], 18 } 19 print('brefore',dic) 20 new_dic = copy.copy(dic) 21 new_dic = copy.deepcopy(dic) 22 new_dic['cpu'][0] = 50 23 print(dic) 24 print(new_dic) 25 #浅拷贝 {'disk': [80], 'mem': [80], 'cpu': [50]} 26 # {'disk': [80], 'mem': [80], 'cpu': [50]} 27 #深拷贝 {'cpu': [80], 'mem': [80], 'disk': [80]} 28 # {'cpu': [50], 'mem': [80], 'disk': [80]}