python中的深拷贝与浅拷贝解析

一、赋值,传递对象的引用

>>> a = [1, 2, 3, 4, ['a', 'b']]
>>> b = a
>>> b is a
True

b就是a ,两者同步改变

二、浅拷贝

>>> a = [1,2,3,[4,5]]
>>> b = list(a)#######或者是b = copy.copy(a)
>>> b
[1, 2, 3, [4, 5]]
>>> a is b
False
>>> b[3][0] = 100#####嵌套的值改变时,影响到原值,两者同步改变
>>> b
[1, 2, 3, [100, 5]]
>>> a
[1, 2, 3, [100, 5]]
>>> [id(x) for x in a]
[29982856, 29982844, 29982832, 39308384]
>>> [id(x) for x in b]
[29982856, 29982844, 29982832, 39308384]

>>> b[0] = 8#######第一层的值改变时,不影响原值。
>>> b
[8, 2, 3, [100, 5]]
>>> a
[1, 2, 3, [100, 5]]

复制了a的引用,只能做到顶层的复制,不能复制嵌套的数据。所以当b的顶层数据改变时,a不变,当嵌套的数据改变时,a也改变。

切片也属于浅拷贝。

三、深拷贝

>>> b = copy.deepcopy(a)
>>> b is a
False
>>> b[3][0] = 100
>>> a
[1, 2, 3, [4, 5]]
>>> b
[1, 2, 3, [100, 5]]
>>> b[0] = 8
>>> a
[1, 2, 3, [4, 5]]
>>> b
[8, 2, 3, [100, 5]]
>>> 

Copy.deepcopy() 可以拷贝完整的数据结构, b 改变时不影响




你可能感兴趣的:(python,拷贝)