码迷,mamicode.com
首页 > 编程语言 > 详细

Python 中的浅拷贝和深拷贝

时间:2017-11-18 11:16:49      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:字典   mil   style   ict   span   list   bsp   div   import   

 

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 中的浅拷贝和深拷贝

标签:字典   mil   style   ict   span   list   bsp   div   import   

原文地址:http://www.cnblogs.com/gaowengang/p/7855941.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!