十七、深浅copy
-
浅copy:list dict:嵌套的可变数据类型是同一个
-
深copy:list dict:嵌套的可变数据类型不是同一个
-
python对深copy做了一个优化,将不可变的数据类型沿用同一个
# 赋值运算
l1 = [1, 2, 3, [22, 33]]
l2 = l1
l1.append(666)
print(l1) #[1, 2, 3, [22, 33], 666]
print(l2) #[1, 2, 3, [22, 33], 666]
# 浅copy
l1 = [1, 2, 3, [22, 33]]
l2 = l1.copy()
l1.append(666)
print(l1,id(l1)) #[1, 2, 3, [22, 33], 666] 2636121985672
print(l2,id(l2)) #[1, 2, 3, [22, 33]] 2636122977992
l1 = [1, 2, 3, [22, 33]]
l2 = l1.copy()
l1[-1].append(666)
print(id(l1[-1])) #2769458001672
print(id(l2[-1])) #2769458001672
print(id(l1[0])) #1785949200
print(id(l2[0])) #1785949200
print(l1) #[1, 2, 3, [22, 33, 666]]
print(l2) #[1, 2, 3, [22, 33, 666]]
l1 = [1, 2, 3, [22, 33]]
l2 = l1.copy()
l1[0] = 90
print(l1) #[90, 2, 3, [22, 33]]
print(l2) #[1, 2, 3, [22, 33]]
# 深copy
import copy
l1 = [1, 2, 3, [22, 33]]
l2 = copy.deepcopy(l1)
print(id(l1)) #2258605313352
print(id(l2)) #2258605615048
l1[-1].append(666)
print(l1) #[1, 2, 3, [22, 33, 666]]
print(l2) #[1, 2, 3, [22, 33]]
# 相关面试题;
l1 = [1, 2, 3, [22, 33]]
l2 = l1[:]
l1[-1].append(666)
print(l1) #[1, 2, 3, [22, 33, 666]]
print(l2) #[1, 2, 3, [22, 33, 666]]
-
浅copy:在内存中开辟一个新的空间存放copy的对象(列表,字典),但是里面所有的元素与被copy对象的里面的元素共用一个
-
深copy:不可变的数据类型沿用之前的,可变的数据类型创建新的