简述python深浅拷贝
作者:互联网
# 赋值
a = 1
b = a
print(a, b)
print(id(a), id(b)) # id是相同的
c = [1, 2, 3]
d = c
c[0] = "xiongsheng"
print(c, d)
# 浅拷贝
import copy
li1 = [1, 2, 3]
li2 = copy.copy(li1)
li1[0] = "xiongsheng"
print(li1, li2)
li3 = [[11, 22, 33], [44, 55, 66]]
li4 = copy.copy(li3)
li3[0][0] = "xiongsheng"
print(li3, li4) # 浅拷贝只是拷贝了第一层
# 深拷贝
li5 = [111, 222, 333], [444, 555, 666]
li6 = copy.deepcopy(li5)
li5[0][0] = "xiongsheng"
print(li5, li6) # 深拷贝全部都拷贝了
# 总结: 浅拷贝只拷贝第一层数据 深拷贝中可变数据类型共用的是一个,不可变的数据类型会从新开辟一个新的空间
标签:python,xiongsheng,li5,简述,li1,print,拷贝,copy 来源: https://www.cnblogs.com/xiongsheng/p/15881648.html