Once, in helping seniors do the problem, a bug has not been adjusted, and then after several twists and turns, finally have the results. Now put the pits in them, share out. In fact, the main is the deep copy in Python and shallow copy understanding of the resulting deviation.
Python comes with a copy module, which is used to perform deep and shallow copies.
Shallow copy:
L1 = [1,2,3,4]l2= L1#L2 Reference L1, which actually points to the same objectPrint(L2)#[1, 2, 3, 4]L1[0] = 99#The operation of the L2 is the operation of the L1.Print(L1)#[© 2, 3, 4]Print(L2)#[© 2, 3, 4]###################### fromCopyImportCOPYL1= [1, 2, [3, 4]]#Object that contains the objectL2 =copy (L1)Print(L2)#[1, 2, [3, 4]]Print(L1)#[1, 2, [3, 4]]L2[2][0] = 99Print(L1)#[1, 2, [4]]Print(L2)#[1, 2, [4]]L1[1] = 88Print(L1)#[1, [4]]Print(L2)#[1, 2, [4]]
Deep copy:
from Import = [1, 2, 3, 4# L2 pointing to L1 new object print(L2)# [1, 2, 3, 4]
l2[0] = L2 operation does not affect L1print(L1)# [1, 2, 3, 4] Print(L2)# [© 2, 3, 4]
Copy of list in Python:
One: Very strange grammar
New_list = old_list[:]
II: Built-in list () function
New_list = List (old_list)
Three: Copy
This is a bit slower than list () because it's going to find the type of old_list.
Import= copy.copy (old_list)
Four: Slowest and most memory-consuming methods, but sometimes necessary
Import= copy.deepcopy (old_list)
Deep and shallow copies in Python