首页 > 编程语言 > 详细

Python3的深拷贝和浅拷贝

时间:2019-04-14 15:20:24      阅读:76      评论:0      收藏:0      [点我收藏+]
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
"""

Python3的深拷贝和浅拷贝

原文:https://www.cnblogs.com/hellomrr/p/10705072.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!