The examples in this article describe Python replication and reference usage. Share to everyone for your reference. The specific analysis is as follows:
Simple replication is a reference
a=[1,23,4]
b=a #这是引用
b.append (2323)
print (a,b) # ([1, 23, 4, 2323], [1, 23, 4, 2323])
Using copy.copy for shallow copies
Import Copy
c=copy.copy (b) #拷贝
c.append (1)
print (b,c) # ([1, 4, 2323], [1,, 4, 2323, 1])
list1=[[' A '],[1,2,4],[23, ' a ']]
list_copy=copy.copy (list1)
#浅拷贝, generates a new object, but the properties and content within the new object are still references to the original object
When the new object is modified as a whole, it is itself
list_copy.append (' append ')
print (list_copy) #[[' A ', [1, 2, 4], [a], ' append ']
print (List1) #[[' a '], [1, 2, 4], [, ' a ']]
#当对新对象的内容进行修改的时候修改的是原对象, because it is still a reference
list_copy[1].append (' Append+ ')
print (list_copy) #[[' a '], [1, 2, 4, ' append+ '], [B, ' a '], ' append ']
print (list1) #[[' a '], [1, 2, 4, ' a Ppend+ '], [B, ' a ']]
By using Copy.deepcopy to iterate over the copy, you can then change the properties of the new object without affecting the original object, except that the efficiency is reduced and memory occupancy increases.
It is the simplest and most direct and efficient way for List,dict,set to use X (object) and object for the corresponding type.
I hope this article will help you with your Python programming.