赋值拷贝,浅拷贝与深拷贝
赋值拷贝 [引用拷贝]
特点:拷贝出来的新的列表与原本列表,他们两个共用同一块内存,
若列表发生变化,则同时进行改变.
list1 = [1,2,3,4,[1,2,3]]
list2 = list1
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list2) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(id(list1)) # 输出结果 2329447376520
print(id(list2)) # 输出结果 2329447376520
list2[-1][-1] = 1
print(list2) # 输出结果 [1, 2, 3, 4, [1, 2, 1]]
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 1]]
print(id(list1)) # 输出结果 2329447376520
print(id(list2)) # 输出结果 2329447376520
list2[-1] = "hello"
print(list2) # 输出结果 [1, 2, 3, 4, 'hello']
print(list1) # 输出结果 [1, 2, 3, 4, 'hello']
print(id(list1)) # 输出结果 2329447376520
print(id(list2)) # 输出结果 2329447376520
浅拷贝
特点:对于一维列表,会开辟新的内存空间,拷贝出来的新的列表与原本的列表id并不相同,
但是这仅限于一维列表.这种拷贝方式是一种不完全拷贝.
若出现二维列表,有可能仍然会出现共用内存的情况.
import copy
list1 = [1,2,3,4,[1,2,3]]
list3 = list1.copy()
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list3) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(id(list1)) # 输出结果 1975663482504
print(id(list3)) # 输出结果 1975663504008
list3[0] = 2
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list3) # 输出结果 [2, 2, 3, 4, [1, 2, 3]]
print(id(list1)) # 输出结果 1975663482504
print(id(list3)) # 输出结果 1975663504008
list3[-1][-1] = "good"
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 'good']]
print(list3) # 输出结果 [2, 2, 3, 4, [1, 2, 'good']]
print(id(list1)) # 输出结果 1975663482504
print(id(list3)) # 输出结果 1975663504008
深拷贝
特点:是一种完全拷贝,它重新递归开辟一块新的内存空间,若出现多维列表的情况下,
多维列表的内存也会重新复制一份.新的列表与原列表不会出现共用内存的情况.
import copy
list1 = [1,2,3,4,[1,2,3]]
list4 = copy.deepcopy(list1)
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list4) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(id(list1)) # 输出结果 1968912750216
print(id(list4)) # 输出结果 1968912771720
list4[0] = 5
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list4) # 输出结果 [5, 2, 3, 4, [1, 2, 3]]
print(id(list1)) # 输出结果 1968912750216
print(id(list4)) # 输出结果 1968912771720
list4[-1][-1] = "nice"
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list4) # 输出结果 [5, 2, 3, 4, [1, 2, 'nice']]
print(id(list1)) # 输出结果 1968912750216
print(id(list4)) # 输出结果 1968912771720