深浅拷?
Posted ajie-boby
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了深浅拷?相关的知识,希望对你有一定的参考价值。
一.深浅拷?
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
都不?样了. 深度拷?. 把元素内部的元素完全进?拷?复制. 不会产??个改变另?个跟着
改变的问题
考点
a = [1, 2] a[1] = a print(a[1])
以上是关于深浅拷?的主要内容,如果未能解决你的问题,请参考以下文章