python中的深浅拷贝

举例说明:

# 引入copy模块
import copy
lst1 = [1, 2, 3, ["a", "b"]]
# 赋值操作
lst2 = lst1

# 切片操作,会产生新的列表-浅拷贝
lst3 = lst1[:]
lst4 = lst1.copy()
lst5 = copy.deepcopy(lst1)

lst1.append(4)
lst1[3].append("c")
print(lst1)
print(lst2)
print(lst3)
print(lst4)
print(lst5)
print(id(lst1))
print(id(lst2))
print(id(lst3))
print(id(lst4))
print(id(lst5))
# 浅拷贝后嵌套列表的内存地址一致
print(id(lst1[3]))
print(id(lst4[3]))
# 深拷贝后嵌套列表的内存地址一致
print(id(lst1[3]))
print(id(lst5[3]))

运行结果:

[1, 2, 3, ['a', 'b', 'c'], 4]
[1, 2, 3, ['a', 'b', 'c'], 4]
[1, 2, 3, ['a', 'b', 'c']]
[1, 2, 3, ['a', 'b', 'c']]
[1, 2, 3, ['a', 'b']]
2251874503176
2251874503176
2251875870472
2251875870408
2251875870344
2251874503880
2251874503880
2251874503880
2251875870280

总结:

# 1. 赋值操作. 没有创建新对象
# 2. 浅拷贝. 只拷贝第一层内容. [:]   copy()
# 3. 深拷贝. 把这个对象内部的内容全部拷贝一份. 引入copy模块. deepcopy()

 

posted @ 2020-06-28 15:56  奔奔-武  阅读(188)  评论(0编辑  收藏  举报