Blog·Tanky WooABOUTRSS

Python的浅复制(Shallow Copy)和深复制(Deep Copy)

18 Apr 2012
这篇博客是从旧博客 WordPress 迁移过来,内容可能存在转换异常。

看看官方的讲解:

Python v2.7.2 documentation » The Python Standard Library » 8. Data Types » 8.17. copy — Shallow and deep copy operations

copy.copy(x) 
Return a shallow copy of x. 

copy.deepcopy(x) 
Return a deep copy of x.  

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

Shallow copies of dictionaries can be made using dict.copy(), and of lists by assigning a slice of the entire list, for example, copiedlist = originallist[:].

举例(IPython):

先看看浅复制(Shallow Copy):

In [1]: import copy 
In [2]: a = [1,2,3,[4,5,6,[7,8,9]]] 
In [3]: b = copy.copy(a) 
In [4]: print a  
[1, 2, 3, [4, 5, 6, [7, 8, 9]]] 
In [5]: print b  
[1, 2, 3, [4, 5, 6, [7, 8, 9]]] 
In [6]: b[0] = 10 
In [7]: print b  
[10, 2, 3, [4, 5, 6, [7, 8, 9]]] 
In [8]: print a  
[1, 2, 3, [4, 5, 6, [7, 8, 9]]]  # a没有变化
In [9]: b[3][0] = 11 
In [10]: print b  
[10, 2, 3, [11, 5, 6, [7, 8, 9]]] 
In [11]: print a  
[1, 2, 3, [11, 5, 6, [7, 8, 9]]]  # a有变化

再来看看深复制(Deep Copy):

In [1]: import copy 
In [2]: a = [1,2,3,[4,5,6,[7,8,9]]] 
In [3]: b = copy.deepcopy(a) 
In [4]: print a  
[1, 2, 3, [4, 5, 6, [7, 8, 9]]] 
In [5]: print b  
[1, 2, 3, [4, 5, 6, [7, 8, 9]]] 
In [6]: b[3][0] = 11 
In [7]: print b  
[1, 2, 3, [11, 5, 6, [7, 8, 9]]] 
In [8]: print a  
[1, 2, 3, [4, 5, 6, [7, 8, 9]]]  # a没变化

三篇参考:

http://docs.python.org/library/copy.html

http://blog.csdn.net/sharkw/article/details/1934090

http://ebkk.blog.163.com/blog/static/19413508520097266592180/