深浅拷贝
深浅拷贝 -- 复制
面试必问:赋值、浅拷贝、深拷贝
浅拷贝:.copy / lst[:]
lst = [1,2,3,[5, 6, 7]]
lst1 = lst
print(lst1)
print(lst)
lst[-1].append(8)
print(lst1)
print(lst)
lst = [1, 2, 3, [5, 6, 7]]
lst1 = lst.copy() # 新开辟一个空间给lst1
print(lst)
print(id(lst))
print(lst1)
print(id(lst1))
print(lst[0])
print(lst1[0])
print(id(lst[0]))
print(id(lst1[0]))
浅拷贝的时候,只会开辟一个新的容器列表,其他元素使用的都是原列表中的元素
lst = [1, 2, 3, [5, 6, 7]]
lst1 = lst.copy()
lst1[-1].append(8)
print(lst)
print(lst1)
lst = [1, 2, 3, [5, 6, 7]]
lst1 = lst.copy()
lst[0] = 11
print(lst1)
print(lst)
lst = [1, 2, 3, [5, 6, 7]]
lst1 = lst.copy()
lst[3] = 567
print(lst)
print(lst1)
lst = [1, 2, 3, 4, [5, 6, 7, [8, 9]]]
lst1 = lst.copy()
lst1.append(10)
print(lst) # [1, 2, 3, 4, [5, 6, 7, [8, 9]]]
print(lst1) # [1, 2, 3, 4, [5, 6, 7, [8, 9]], 10]
lst = [[1, 2], 90, 6, 7, [5, 6]]
lst1 = lst.copy()
lst1[0].append(8)
print(lst)
print(lst1)
dic = {"xieyulin": "50"}
dic1 = dic.copy()
dic["yilin"] = "10"
print(dic)
print(dic1)
dic = {"xieyulin": [1, 2, 3, [5, 6]]}
dic1 = dic.copy()
dic["xieyulin"][-1].append(0)
print(dic)
print(dic1)
dic = {"xieyulin": [1, 2, 3, [5, 6]]}
dic1 = dic.copy()
dic["xieyulin"][-1] = 0
print(dic)
print(dic1)
dic = {"xieyulin": [1, 2, 3, [5, 6]]}
dic1 = dic.copy()
dic["xieyulin"] = 0
print(dic)
print(dic1)
浅拷贝的时候,只拷贝第一层元素
浅拷贝在修改第一层元素(不可变数据类型)的时候,拷贝出来的新列表不进行改变
浅拷贝在替换第一层元素(可变数据类型)的时候,拷贝出来的新列表不进行改变
浅拷贝在修改第一层元素中的元素(第二层)的时候,拷贝出来的新列表进行改变
深拷贝:
import copy # 导入 copy是个模块
lst = [1, 2, 3, [5, 6, 7]]
lst1 = copy.deepcopy(lst) # 深拷贝
lst[0] = '123'
print(lst)
print(lst1) # 没变,同浅拷贝
lst = [1, 2, 3, [5, 6, 7]]
lst1 = copy.deepcopy(lst) # 深拷贝
lst[-1] = '123'
print(lst)
print(lst1) # 没变,同浅拷贝
lst = [1, 2, 3, [5, 6, 7]]
lst1 = copy.deepcopy(lst) # 深拷贝
lst[-1].append(8)
print(lst) # [1, 2, 3, [5, 6, 7, 8]]
print(lst1) # 没变 [1, 2, 3, [5, 6, 7]]
深拷贝开辟一个容器空间(列表),不可变数据公用,可变数据数据类型(再次开辟一个新的空间),空间里的值使用的是不可变的数据进行公用,可变的数据类型再次开辟空间

浙公网安备 33010602011771号