python 拷贝

 

copy — Shallow and deep copy operations

  Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

    Python中的赋值都是传引用,也就是赋值后两个值都是指向同一个对象。

    如果想要一份独立的拷贝,需要用到copy模块:

Interface summary:

copy.copy(x)         Return a shallow copy of x.
copy.deepcopy(x)      Return a deep copy of x.
exception copy.error   Raised for module specific errors.

    在自己实现的类中可以通过实现__copy__() , __deepcopy__()来定制copy。

    对于list,map和set有简单的拷贝方式:

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[:]. 

dict.copy()

set.copy()

list[:]   

  To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

  如果在遍历容器的同时有对容器进行操作,那一定记得使用拷贝

>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

 

 

 

 

 

 

 

 

 

 

 

posted @ 2013-05-09 10:11  tangr206  阅读(291)  评论(0编辑  收藏  举报