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

看看官方的讲解:

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

 

[code language=”python”]
copy.copy(x)
Return a shallow copy of x.

copy.deepcopy(x)
Return a deep copy of x.
[/code]

 

 

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

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

 

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

 

举例(IPython):

先看看浅复制(Shallow Copy):

[code language=”python”]
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有变化
[/code]

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

[code language=”python”]
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没变化
[/code]

三篇参考:

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

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

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

发布者

Tanky Woo

Tanky Woo,[个人主页:https://tankywoo.com] / [新博客:https://blog.tankywoo.com]

发表评论

电子邮件地址不会被公开。 必填项已用*标注