Python3的深拷贝和浅拷贝
生活随笔
收集整理的這篇文章主要介紹了
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
"""
轉載于:https://www.cnblogs.com/hellomrr/p/10705072.html
總結
以上是生活随笔為你收集整理的Python3的深拷贝和浅拷贝的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开发步骤 采用restful接口开发的开
- 下一篇: Java交换两个Integer-一道无聊