copy 浅拷贝和深拷贝
Posted 独孤_败天
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了copy 浅拷贝和深拷贝相关的知识,希望对你有一定的参考价值。
1 #直接赋值和 copy 的区别 2 dic1={‘name‘: ‘Tom‘, ‘age‘: 18, ‘hobby‘: ‘running‘} 3 dic2=dic1 4 5 print(dic1) 6 print(dic2) 7 8 #修改数据 age=28 9 dic1[‘age‘]=28 10 11 print(dic1) 12 print(dic2) 13 # 浅拷贝: 引用对象 dic2只是对dic1的引用。所以当dic1的值改变,dic2也会随着改变 14 15 16 dic3={‘name‘: ‘Tom‘, ‘age‘: 18, ‘hobby‘: ‘running‘} 17 18 dic4=dic3.copy() 19 #浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用 20 print(dic3) 21 print(dic4) 22 #修改数据 age=38 23 dic3[‘age‘]=38 24 25 print(dic3) 26 print(dic4) 27 28 dic5={‘name‘: [‘Tom‘,‘Jack‘], ‘age‘:[ 18,28], ‘hobby‘: [‘running‘,‘football‘]} 29 30 dic6=dic5.copy() 31 32 #浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用 33 print(dic5) 34 print(dic6) 35 #修改一级目录(父对象),修改数据 [‘running‘,‘football‘]修改为[‘basketball‘] 36 dic5[‘hobby‘]=[‘basketball‘,] 37 38 #修改二级目录(子对象),修改数据 Tom 改成 May 39 dic5[‘name‘][0]=‘May‘ 40 dic5[‘age‘][0]=38 41 42 print(dic5) 43 print(dic6)
结果:
{‘name‘: ‘Tom‘, ‘age‘: 18, ‘hobby‘: ‘running‘} {‘name‘: ‘Tom‘, ‘age‘: 18, ‘hobby‘: ‘running‘} {‘name‘: ‘Tom‘, ‘age‘: 28, ‘hobby‘: ‘running‘} {‘name‘: ‘Tom‘, ‘age‘: 28, ‘hobby‘: ‘running‘} {‘name‘: ‘Tom‘, ‘age‘: 18, ‘hobby‘: ‘running‘} {‘name‘: ‘Tom‘, ‘age‘: 18, ‘hobby‘: ‘running‘} {‘name‘: ‘Tom‘, ‘age‘: 38, ‘hobby‘: ‘running‘} {‘name‘: ‘Tom‘, ‘age‘: 18, ‘hobby‘: ‘running‘} {‘name‘: [‘Tom‘, ‘Jack‘], ‘age‘: [18, 28], ‘hobby‘: [‘running‘, ‘football‘]} {‘name‘: [‘Tom‘, ‘Jack‘], ‘age‘: [18, 28], ‘hobby‘: [‘running‘, ‘football‘]} {‘name‘: [‘May‘, ‘Jack‘], ‘age‘: [38, 28], ‘hobby‘: [‘basketball‘]} {‘name‘: [‘May‘, ‘Jack‘], ‘age‘: [38, 28], ‘hobby‘: [‘running‘, ‘football‘]}
以上是关于copy 浅拷贝和深拷贝的主要内容,如果未能解决你的问题,请参考以下文章