标签:epc pre 实现 深浅拷贝 李嘉诚 col int nbsp 结果
深浅拷贝
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)) 结果: 两个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
都不一样了. 深度拷贝. 把元素内部的元素完全进行拷贝复制. 不会产生一个改变另一个跟着改变的问题
标签:epc pre 实现 深浅拷贝 李嘉诚 col int nbsp 结果
原文地址:https://www.cnblogs.com/zpf666/p/9670947.html