python中的深拷贝和潜拷贝
2015-06-26 17:43
591 查看
>>> a = ['ace',['age',10]] >>> b = a[:] >>> c = list(a) >>> for item in a: ... print(id(item)) ... 140281621219736 140281621134800 >>> for item in b: print(id(item)) ... 140281621219736 140281621134800 >>> for item in c: print(id(item)) ... 140281621219736 140281621134800
看得出,这里的集中拷贝方式都只是类似指针的引用。。改改试试?
>>> b[0] = 'bog' >>> b ['bog', ['age', 10]] >>> a ['ace', ['age', 10]] >>> c ['ace', ['age', 10]] >>> c[0] = 'cat' >>> a ['ace', ['age', 10]] >>> b ['bog', ['age', 10]] >>> c ['cat', ['age', 10]]
艾,变了。在改改列表?
>>> a ['ace', ['age', 10]] >>> b ['bog', ['age', 10]] >>> c ['cat', ['age', 10]] >>> a[1][1] = 'ago' >>> a ['ace', ['age', 'ago']] >>> b ['bog', ['age', 'ago']] >>> c ['cat', ['age', 'ago']] >>> b[1][1] = 'agy' >>> a ['ace', ['age', 'agy']] >>> b ['bog', ['age', 'agy']] >>> c ['cat', ['age', 'agy']] >>> c[1][1] = 'cat!' >>> a ['ace', ['age', 'cat!']] >>> b ['bog', ['age', 'cat!']] >>> c ['cat', ['age', 'cat!']]
艾玛,全变了。。。什么情况阿!
哈哈,来个总结!
发现,其中列表中 姓名字符串 id都不一样,但是 年龄列表id却都相同。
这是因为:python中字符串不可以修改,所以在为tom和anny重新命名的时候,会重新创建一个’tom’和’anny’对象,替换旧的’jack’对象。
这就说明了,浅复制(shallow copy),它复制了对象,但对于对象中的元素,依然使用引用.
那深拷贝也就是玩玩全全的从内存空间新开辟一个地址存一个副本辣!
怎么用呢?
>>> import copy >>> d = copy.deepcopy(a) >>> for item in a: ... print(id(a)) ... 140281621133432 140281621133432 >>> for item in d: print(id(item)) ... 140281621219736 140281621159160
see!不一样了把
相关文章推荐
- python读取TXT到数组及列表去重后按原来顺序排序的方法
- python编程练习
- python选择排序实现与C选择排序实现
- Python的getattr(),setattr(),delattr(),hasattr()
- Python __slots__
- Python 的内建对象
- Python中print/format字符串格式化实例
- 老鸟的Python入门教程
- Python 学习指南
- Python中用于计算对数的log()方法
- 20150610-Python面试
- MIT Python 第四课函数抽象与递归简介 函数调用与原代码的区别
- python获取当前脚本下的所有方法
- python basic note
- 【python】 开始第一个项目
- python字符串/元组/列表/字典互转
- Python核心编程笔记--unicode编码
- 什么是 WSGI -- Python 中的 “CGI” 接口简介
- Python Django开发 1
- syntax error near unexpected token ?怎么解决