python中的深拷贝和潜拷贝
2024-09-05 21:34:46
>>> 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!不一样了把
最新文章
- 高通android开发缩写
- mysql 触发器的创建 修改 删除
- BZOJ2763[JLOI2011]飞行路线 [分层图最短路]
- iOS 开发 - 改善APP的流畅度 (绘制股票行情)
- JAVA使用POI读取EXCEL文件的简单model
- HDU 1754 单点更新,求区间最大值
- leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal ----- java
- C++异常处理(Exception Handling)
- 周末充电之WPF(二 ) .窗口的布局
- android之GridView实现九宫格布局
- C#使用jmail组件发送邮件
- jquery之遍历展示title
- Servlet实现文件上传(多文件)(三)
- 在PostgreSQL自定义一个“优雅”的type
- Spring Boot 文件上传
- 剑指Offer——网易校招内推笔试题+模拟题知识点总结
- python—day9 函数的定义、操作使用方法、函数的分类、函数的嵌套调用
- linux 保存git的账号密码
- exactly-once和kafka
- nginx反向代理导致请求header头信息丢失