Python3的深拷贝和浅拷贝


a = 1
b = a
a = 2
print(a, b)
print(id(a), id(b))
"""
运行结果
2 1
1445293568 1445293536
"""

# 列表直接复赋值给列表不属于拷贝, 只是内存地址的引用
list1 = ["a", "b", "c"]
list2 = list1
list1.append("d")
print(list1, list2)
print(id(list1), id(list2))
"""
运行结果
['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd']
1947385383176 1947385383176
"""

# 浅拷贝
list1 = ["a", "b", "c"]
list2 = list1.copy()
list1.append("d")
print(list1, list2)
print(id(list1), id(list2))
""" 
运行结果:
['a', 'b', 'c', 'd'] ['a', 'b', 'c']
1553315383560 1553315556936
"""

# 浅拷贝, 只会拷贝第一层, 第二层的内容不会拷贝
list1 = ["a", "b", "c", [1, 2, 3]]
list2 = list1.copy()
list1[3].append(4)
print(list1, list2)
print(id(list1), id(list2))
"""
运行结果
['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3, 4]]
1386655149640 1386655185672
"""

# 深拷贝
import copy  
list1 = ["a", "b", "c", [1, 2, 3]]
list2 = copy.deepcopy(list1)
list1[3].append(4)
print(list1, list2)
print(id(list1), id(list2))
"""
运行结果
['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3]]
1452762592904 1452762606664
"""


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM