Python copy and python copy
Test environment: python 2.7
Use module copy. py
There are two methods in this module
Copy. copy () # Light copy
Copy. deepcopy () # Deep copy
What is the difference between shallow copy and deep copy:
The content of the first layer can only be copied in a shortest copy.
Deep copy can copy content from the outer to the inner n layers
See the example below:
list1 = [1,2,3,4]list2 = list1list1.append(99)print list2
Printed result: list2 = [1, 2, 3, 4, 99]
Note: In python, when a value is assigned to a variable of the reference type, the address is assigned to the variable.
Introduction to the reference type: http://www.cnblogs.com/gametesting/p/7159398.html
To solve this problem, we can use the slice operation:
List2 = list1 [:]
At the same time, we can also introduce the concept of copying only values.
list1 = [1,2,3,4]list2 = copy.copy(list1)list1.append(99)print list2
Printed result: list2 = [1, 2, 4]
When list1 is modified, list2 is not modified.
We can also copy. after copy () is complete, we can see that the memory addresses of the two are different by comparing id (list1) and id (list2, using the shortest copy function is equivalent to copying the value of list1 to a new memory area, and then assigning the value to list2.
However, when list1 = [1, 2, 3, 4, [1, 2] (when the operation object exceeds one dimension ),
We use the shortest copy, and it will be useless.
(Code omitted). After using the shortest copy function, you can find that the value of list1 is modified and the value of list2 is modified.
At this time, we need to use deep copy. deepcopy ()
list1 = [1,2,3,4,[1,2]]list2 = copy.deepcopy(list1)list1[4].append(99)print list2
Print the results to solve the problem perfectly