标签:str pytho 不同的 一级目录 back epc 拷贝 元素 方法
类型属于对象,不是变量
Python中一切皆对象,如:1,‘a‘,[1,2,3],(1,),{‘a‘:4}
a=3,a就是一个变量
a=3,a引用了对象3
深拷贝和浅拷贝分别对应copy模块的两个方法:deepcopy()和copy()
浅拷贝:只拷贝顶级的对象,或者说:父级对象 a=copy.copy(b)
深拷贝:拷贝所有对象,顶级对象及其嵌套对象。或者说:父级对象及其子对象 a=copy.deepcopy(b)
In [38]: dict1={‘name‘:‘tom‘,‘age‘:18} In [39]: import copy In [40]: dict2=copy.copy(dict1) In [41]: dict3=copy.deepcopy(dict1) In [45]: dict2 Out[45]: {‘age‘: 18, ‘name‘: ‘tom‘} In [46]: dict3 Out[46]: {‘age‘: 18, ‘name‘: ‘tom‘} In [52]: id(dict1) Out[52]: 140466748386440 In [53]: id(dict2) Out[53]: 140466741274952 In [54]: id(dict3) Out[54]: 140466749401864 In [47]: dict1[‘age‘]=22 In [48]: dict2 Out[48]: {‘age‘: 18, ‘name‘: ‘tom‘} In [49]: dict3 Out[49]: {‘age‘: 18, ‘name‘: ‘tom‘} In [50]: dict1 Out[50]: {‘age‘: 22, ‘name‘: ‘tom‘} ## 可以看到源字典dict1变了,而深、浅拷贝都没有变
In [55]: dict1={‘name‘:{‘first‘:‘tom‘,‘second‘:‘jerry‘},‘city‘:[‘NY‘,‘LA‘]} In [56]: import copy In [57]: dict2=copy.copy(dict1) In [58]: dict3=copy.deepcopy(dict1) In [59]: id(dict1) Out[59]: 140466746666568 In [60]: id(dict2) Out[60]: 140466746816072 In [61]: id(dict3) Out[61]: 140466746724296 In [62]: dict1 Out[62]: {‘city‘: [‘NY‘, ‘LA‘], ‘name‘: {‘first‘: ‘tom‘, ‘second‘: ‘jerry‘}} In [63]: dict2 Out[63]: {‘city‘: [‘NY‘, ‘LA‘], ‘name‘: {‘first‘: ‘tom‘, ‘second‘: ‘jerry‘}} In [64]: dict3 Out[64]: {‘city‘: [‘NY‘, ‘LA‘], ‘name‘: {‘first‘: ‘tom‘, ‘second‘: ‘jerry‘}} In [65]: dict1[‘name‘][‘first‘]=‘john‘ In [66]: dict2 Out[66]: {‘city‘: [‘NY‘, ‘LA‘], ‘name‘: {‘first‘: ‘john‘, ‘second‘: ‘jerry‘}} In [67]: dict3 Out[67]: {‘city‘: [‘NY‘, ‘LA‘], ‘name‘: {‘first‘: ‘tom‘, ‘second‘: ‘jerry‘}} In [68]: dict1 Out[68]: {‘city‘: [‘NY‘, ‘LA‘], ‘name‘: {‘first‘: ‘john‘, ‘second‘: ‘jerry‘}}
所以:
标签:str pytho 不同的 一级目录 back epc 拷贝 元素 方法
原文地址:https://www.cnblogs.com/zh-dream/p/13352535.html