标签:
参考:http://www.cnblogs.com/Eva-J/p/5534037.html
对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。(可以把数字,字符串看作是内存中最小的地址)
对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。浅拷贝只拷贝第一层地址,而深拷贝是不管你数据结构多么复杂,都在内存里开辟一块新的空间,直到简单数据类型为止。
以这个字典为例:
dict = {"k1":"mu","k2":23,"k3":["alex",123]}
赋值 |
dict = {"k1":"mu","k2":23,"k3":["alex",123]} dict1=dict print(id(dict)) print(id(dict1)) 输出结果: 2243042460872 2243042460872
浅拷贝 |
import copy dict = {"k1":"mu","k2":23,"k3":["alex",123]} dict2=copy.copy(dict) print(id(dict)) print(id(dict2)) print(id(dict[‘k3‘])) print(id(dict2[‘k3‘])) 输出结果: 2053865129160 2053865571208 2053867015560 2053867015560
深拷贝 |
import copy dict = {"k1":"mu","k2":23,"k3":["alex",123]} dict3 = copy.deepcopy(dict) print(id(dict)) print(id(dict3)) print(id(dict[‘k3‘])) print(id(dict3[‘k3‘])) 输出结果: 3045244716232 3045245124744 3045246601736 3045246600456
深浅copy的应用举例:
1 import copy 2 dic = { 3 "cpu":[80,], 4 "mem":[80,], 5 ‘disk‘:[80,] 6 } 7 print(‘before:‘,dic) 8 new_dic = copy.copy(dic) 9 new_dic[‘cpu‘][0] = 50 10 print(dic) 11 print(new_dic) 12 输出结果: 13 before: {‘disk‘: [80], ‘cpu‘: [80], ‘mem‘: [80]} 14 {‘disk‘: [80], ‘cpu‘: [50], ‘mem‘: [80]} 15 {‘disk‘: [80], ‘cpu‘: [50], ‘mem‘: [80]}
1 import copy 2 dic = { 3 "cpu":[80,], 4 "mem":[80,], 5 ‘disk‘:[80,] 6 } 7 print(‘before:‘,dic) 8 new_dic = copy.deepcopy(dic) 9 new_dic[‘cpu‘][0] = 50 10 print(dic) 11 print(new_dic) 12 输出结果: 13 before: {‘cpu‘: [80], ‘mem‘: [80], ‘disk‘: [80]} 14 {‘cpu‘: [80], ‘mem‘: [80], ‘disk‘: [80]} 15 {‘cpu‘: [50], ‘mem‘: [80], ‘disk‘: [80]}
标签:
原文地址:http://www.cnblogs.com/mumuzi1990/p/5803941.html