Python assignment list and array shallow vs. deep copy examples explain

Quote: https://www.jb51.net/article/142775.htm

List assignment:

1
2
3
4
5
6
7
>>> a = [ 1 , 2 , 3 ]
>>> b = a
>>> print b
[ 1 , 2 , 3 ]
>>> a[ 0 ] = 0
>>> print b
[ 0 , 2 , 3 ]

Explanation: [1, 2, 3] is regarded as an object, a, b are the object of this reference, therefore, to change a [0], b also changed

If you want to b does not change, you can use sliced

1
2
3
4
>>> b = a[:]
>>> a[ 0 ] = 0
>>> print b
[ 1 , 2 , 3 ]

Explained, a slice [:] will generate a new object, a new memory occupied, b point to the new memory area, thus changing the value of a pointed object, does not affect b

List of deep copy and shallow copy

Shallow copy

1
2
3
4
5
6
7
8
>>> import copy
>>> a = [ 1 , 2 , 3 , [ 5 , 6 ]]
>>> b = copy.copy(a)
>>> print b
[ 1 , 2 , 3 , [ 5 , 6 ]]
>>> a[ 3 ].append( 'c' )
>>> print b
[ 1 , 2 , 3 , [ 5 , 6 , 'c' ]]

Deep copy

1
2
3
4
5
>>> a = [ 1 , 2 , 3 , [ 5 , 6 ]]
>>> b = copy.deepcopy(a)
>>> a[ 3 ].append( 'c' )
>>> print b
[ 1 , 2 , 3 , [ 5 , 6 ]]

That is, it opens up a new copy of the memory space, copying the values ​​are copied object in the past. Shallow copy and not as a child object [5,6] has opened a new memory space, but only realized in a reference [5,6] of. Therefore, a change in the value of [5,6], the value of b will vary.

Deep copy is for the child object also opened up a new space. Therefore, a change in the value of [5, 6], and does not affect b

Array slice assignment can not be used to achieve the same purpose

1
2
3
4
5
6
>>> import numpy as np
>>> a = np.array([ 1 , 2 , 3 ])
>>> b = a[:]
>>> a[ 0 ] = 5
>>> print a, b
[ 5 2 3 ] [ 5 2 3 ]

As above, although with a slice, but it can not reach a modified without affecting the object b. Description a, b still points to the same memory.

In this case, only a copy

1
2
3
4
>>> b = a.copy()
>>> a[ 0 ] = 5
>>> print a, b
[ 5 2 3 ] [ 1 2 3 ]

In this case a modification does not affect b. The reason to go into further later.

Note that, the copy list copy.copy (obj) or copy.deepcopy (obj), the array is copied obj.copy ()

Above this assignment lists and arrays in Python, a shallow copy and deep copy example to explain that the small series to share the entire contents of everyone, and I hope to give you a reference, I hope you will support script home.

Guess you like

Origin www.cnblogs.com/Sweepingmonk/p/11599297.html