Python 中的浅拷贝和深拷贝

Posted Anonymous

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 中的浅拷贝和深拷贝相关的知识,希望对你有一定的参考价值。

 

1. 列表和字典,直接赋值,都是浅拷贝,即赋值双方指向同一地址,因为 Python 对可变对象按引用传递。

>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]
>>> a[0] = apple
>>> a
[apple, 2, 3]
>>> b
[apple, 2, 3]
>>> 
>>> 
>>> dic = {a: apple, b: banbana}
>>> dic2 = dic
>>> dic2
{a: apple, b: banbana}
>>> dic[b] = blueberry
>>> dic
{a: apple, b: blueberry}
>>> dic2
{a: apple, b: blueberry}

 

2. 对非嵌套的列表,使用完全切片[:], 工厂函数 list(),或者 copy.copy() 都是深拷贝。

>>> a = [1, 2, 3]
>>> b = list(a)
>>> c = a[:]
>>> import copy
>>> d = copy.copy(a)
>>> 
>>> a[0] = apple
>>> a
[apple, 2, 3]
>>> b
[1, 2, 3]
>>> c
[1, 2, 3]
>>> d
[1, 2, 3]

 

3. 对于非嵌套的字典,使用工厂函数 dict(),或者 copy.copy() 都是深拷贝。

>>> dic = {a: apple, b: banana}
>>> dic2 = dict(dic)
>>> import copy
>>> dic3 = copy.copy(dic)
>>> 
>>> dic[b] = blueberry
>>> dic
{a: apple, b: blueberry}
>>> dic2
{a: apple, b: banana}
>>> dic3
{a: apple, b: banana}

 

4. 对于嵌套的列表,嵌套的字典,只能使用 copy.deepcopy() 实现深拷贝。

>>> import copy
>>> 
>>> a = [1, 2, [apple]]
>>> b = copy.deepcopy(a)
>>> a[2][0] = watermelon
>>> a
[1, 2, [watermelon]]
>>> b
[1, 2, [apple]]
>>> 
>>> 
>>> dic = {a: apple, b: {b1: banana, b2: blueberry}}
>>> dic2 = copy.deepcopy(dic)
>>> dic[b][b1] = bukeneng
>>> dic
{a: apple, b: {b1: bukeneng, b2: blueberry}}
>>> dic2
{a: apple, b: {b1: banana, b2: blueberry}}

 

5. 对于嵌套可变对象的元组,只有 copy.deepcopy() 实现深拷贝。

>>> import copy
>>>
>>> t = (1, 2, [apple]) >>> t2 = t >>> t3 = tuple(t) >>> t4 = copy.copy(t) >>> t5 = copy.deepcopy(t) >>> >>> t[2][0] = watermelon >>> t (1, 2, [watermelon]) >>> t2 (1, 2, [watermelon]) >>> t3 (1, 2, [watermelon]) >>> t4 (1, 2, [watermelon]) >>> t5 (1, 2, [apple])

 

完。

 

以上是关于Python 中的浅拷贝和深拷贝的主要内容,如果未能解决你的问题,请参考以下文章

Python 中的浅拷贝和深拷贝

Python面试②——Python中的浅拷贝与和深拷贝

C#的浅拷贝和深拷贝

数据分析系列 之python中的浅拷贝和深拷贝

理解一下python中的浅copy和深copy

python的浅拷贝和深拷贝