day07- copy depth

3.1 shallow copy

list1 = [ 'Egon', 'lxx', [1,2]]

1, two spaced apart not, list list2 followed the change, because the same address is directed
 list2 = list1 # this is not called Copy
 List1 [0] = 'EGON'
 Print (list2)

2, demand:
 1, what the original copy of the list to produce a new list of
 2, wants to open two completely independent list, and for a change, rather than the independent operation of the read operation


3, how to copy listing
 3.1 Shallow copy: the original list is the memory address of the first layer without distinction to completely copy a new list
list1 = [ 'egon', ' lxx', [1,2]]

list3=list1.copy()
print(list3)
print(id(list1))
print(id(list3))

print(id(list1[0]),id(list1[1]),id(list1[2]))
print(id(list3[0]),id(list3[1]),id(list3[2]))

Experiment 1: For immutable types of assignments are created new value, so that the original list of index point to the new
 memory address, and will not affect the new list
List1 [0] = 'EGON'
List1 [1] = 'LXX'
# list1 [2] = 123

Experiment 2: But for the variable type, we can change the value of the variable type is included, but the same memory address
 that is pointing to the original list of index still point to the memory address, then followed with a new list by
 the impact, as follows
 list1 [ 2] [0] = 111
 List1 [2] [. 1] = 222
 Print (List1)
 Print (list3)

Integrated Experiments 1 and 2 can be drawn, change to operate the new list with the original copy of the list in order to get the full independence opened
 there must be a variable types can be distinguished with the type of immutable copy mechanism, which is a deep copy

 


 


3.2 深copy
import copy
list1=['egon','lxx',[1,2]]

list3=copy.deepcopy(list1)
print(id(list1))
print(id(list3))
print(list3)

Immutable immutable Variable
Print (ID (List1 [0]), ID (List1 [. 1]), ID (List1 [2]))
Print (ID (list3 [0]), ID (list3 [. 1]), id (list3 [2]))

'''
4497919088 4498367856 4498449216
4497919088 4498367856 4498595328
'''


print(list3)
print(id(list1[2][0]),id(list1[2][1]))

print(id(list3[2][0]),id(list3[2][1]))

list1[0]='EGON'
list1[1]='LXX'

list1[2][0]=111
list1[2][1]=222
print(list1)

print(list3)

Guess you like

Origin www.cnblogs.com/xiao-zang/p/12450583.html