为了追踪内存中的对象,Python采用了引用计数这一简单技术。变量实际是内存对象的别名,可以看成是C++中引用。当引用计数为0时,该对象就称为垃圾回收机制的回收对象。所以下面的列表复制只是将给列表又起了个别名而已:
- >>> a = [4,5,6,7,9,8,5,2]
- >>> a
- [4, 5, 6, 7, 9, 8, 5, 2]
- >>> b = a
- >>> id(a),id(b)
- (20249936, 20249936)
>>> a = [4,5,6,7,9,8,5,2]
>>> a
[4, 5, 6, 7, 9, 8, 5, 2]
>>> b = a
>>> id(a),id(b)
(20249936, 20249936)
为了得到列表真正的拷贝,可以使用下面几种方法:
方式一:切片操作
- >>> c = a[:]
- >>> id(a),id(c)
- (20249936, 20258128)
>>> c = a[:]
>>> id(a),id(c)
(20249936, 20258128)
方式二:list()函数
- >>> d = list(a)
- >>> id(d),id(a)
- (20245400, 20249936)
>>> d = list(a)
>>> id(d),id(a)
(20245400, 20249936)
方式三: - >>> e = a * 1
- >>> id(a),id(e)
- (20249936, 20250056)
>>> e = a * 1
>>> id(a),id(e)
(20249936, 20250056)
方式四:- >>> import copy
- >>> f = copy.copy(a)
- >>> id(a),id(f)
- (20249936, 20085496)
>>> import copy
>>> f = copy.copy(a)
>>> id(a),id(f)
(20249936, 20085496)
方式五:- >>> x = [1,2,3,[4,5]]
- >>> y = copy.copy(x)
- >>> x[3][1] = 7
- >>> y
- [1, 2, 3, [4, 7]]
- >>> y = copy.deepcopy(x)
- >>> x[3][1] = 9
- >>> y
- [1, 2, 3, [4, 7]]
>>> x = [1,2,3,[4,5]]
>>> y = copy.copy(x)
>>> x[3][1] = 7
>>> y
[1, 2, 3, [4, 7]]
>>> y = copy.deepcopy(x)
>>> x[3][1] = 9
>>> y
[1, 2, 3, [4, 7]]
可以看到,当列表中还有列表时,只有copy.deepcopy()才能得到包括子列表在内的完全拷贝。
REF:http://www.cnblogs.com/ifantastic/p/3811145.html