深浅拷贝
Posted little-raccoon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了深浅拷贝相关的知识,希望对你有一定的参考价值。
lst1 = ["金毛狮王", "紫衫龙王", "白眉鹰王", "青翼蝠王"] lst2 = lst1 print(lst1) print(lst2) lst1.append("杨逍") print(lst1) print(lst2) # 结果: # [‘金毛狮王‘, ‘紫衫龙王‘, ‘白眉鹰王‘, ‘青翼蝠王‘, ‘杨逍‘] # [‘金毛狮王‘ ‘紫衫龙王‘ ‘白眉鹰王‘ ‘青翼蝠王‘ ‘杨逍‘]
dic1 = {"id": 123, "name": "谢逊"} dic2 = dic1 print(dic1) print(dic2) dic1[‘name‘] = "范瑶" print(dic1) print(dic2) # 结果: # {‘id‘: 123, ‘name‘: ‘谢逊‘} # {‘id‘: 123, ‘name‘: ‘谢逊‘} # {‘id‘: 123, ‘name‘: ‘范瑶‘} # {‘id‘: 123, ‘name‘: ‘范瑶‘}
对于list, set, dict来说, 直接赋值. 其实是把内存地址交给变量. 并不是复制一份内容. 所以.
lst1的内存指向和lst2是一样的. lst1改变了, lst2也发生了改变
浅拷贝
lst1 = ["何炅", "杜海涛","周渝民"] lst2 = lst1.copy() lst1.append("李嘉诚") print(lst1) # [‘何炅‘, ‘杜海涛‘, ‘周渝民‘, ‘李嘉诚‘] print(lst2) # [‘何炅‘, ‘杜海涛‘, ‘周渝民‘] print(id(lst1), id(lst2)) # 43601416 43473160
结果:
两个lst完全不一样. 内存地址和内容也不一样. 发现实现了内存的拷贝
lst1 = ["何炅", "杜海涛","周渝民", ["麻花藤", "马芸", "周笔畅"]] lst2 = lst1.copy() lst1[3].append("无敌是多么寂寞") print(lst1) print(lst2) print(id(lst1[3]), id(lst2[3])) # 结果: # [‘何炅‘, ‘杜海涛‘, ‘周渝民‘, [‘麻花藤‘, ‘马芸‘, ‘周笔畅‘, ‘无敌是多么寂寞‘]] # [‘何炅‘, ‘杜海涛‘, ‘周渝民‘, [‘麻花藤‘, ‘马芸‘, ‘周笔畅‘, ‘无敌是多么寂寞‘]] # 4417248328 4417248328
浅拷贝. 只会拷贝第一层. 第二层的内容不会拷贝. 所以被称为浅拷贝
深拷贝
import copy lst1 = ["何炅", "杜海涛","周渝民", ["麻花藤", "马芸", "周笔畅"]] lst2 = copy.deepcopy(lst1) lst1[3].append("无敌是多么寂寞") print(lst1) print(lst2) print(id(lst1[3]), id(lst2[3])) # 结果: # [‘何炅‘, ‘杜海涛‘, ‘周渝民‘, [‘麻花藤‘, ‘马芸‘, ‘周笔畅‘, ‘无敌是多么寂寞‘]] # [‘何炅‘, ‘杜海涛‘, ‘周渝民‘, [‘麻花藤‘, ‘马芸‘, ‘周笔畅‘]] # 4447221448 4447233800
可见深拷贝是把元素内部的元素完全进行拷贝复制,不会产生一个改变另一个跟着改变的问题
以上是关于深浅拷贝的主要内容,如果未能解决你的问题,请参考以下文章