Python3 复制和深浅copy
2024-08-31 23:09:02
赋值:
列表的赋值:
list1 = ['peter','sam']
list2 = list1 print(list1,id(list1))
print(list2,id(list2))
list1.append('hery')
print(list1,id(list1))
print(list2,id(list2)) ['peter', 'sam'] 5071496
['peter', 'sam'] 5071496
['peter', 'sam', 'hery'] 5071496
['peter', 'sam', 'hery'] 5071496
字典的赋值:
dic = {'name':'just'}
dic1 = dic print(dic,id(dic))
print(dic1,id(dic1)) dic['age'] = 27 print(dic,id(dic))
print(dic1,id(dic1)) {'name': 'just'} 38505064
{'name': 'just'} 38505064
{'name': 'just', 'age': 27} 38505064
{'name': 'just', 'age': 27} 38505064
字符串赋值:
str = 'hello'
str1 = str print(str,id(str))
print(str1,id(str1)) str = str.replace('e','E') print(str,id(str))
print(str1,id(str1)) hello 35026176
hello 35026176
hEllo 39638608
hello 35026176
创建两个相同的变量,他们的内存地址相同(以前版本好像是不同)
str = 'h'
str3 = 'h' print(str,id(str))
print(str3,id(str3))
print( str is str3) h 39056528
h 39056528
True
浅copy:
浅copy来说,第一层创建的是新的内存地址。而从第二层开始,指向的是同一个内存地址,所有,对于第二层以及更深的层数来说,保持一致性。
just = ['eric','bob',34,'ida']
dep = ['helo','welcome','jams']
jesp = just.copy() print(just,id(just))
print(jesp,id(jesp)) ['eric', 'bob', 34, 'ida'] 37435528
['eric', 'bob', 34, 'ida'] 37497480
just = ['eric','bob',34,'ida']
dep = ['helo','welcome','jams']
just.append(dep)
jesp = just.copy()
just[1] = 'tom'
jesp[4][0] = 'hi' print(just,id(just))
print(jesp,id(jesp)) ['eric', 'tom', 34, 'ida', ['hi', 'welcome', 'jams']] 42744008
['eric', 'bob', 34, 'ida', ['hi', 'welcome', 'jams']] 43021128
深copy:
对深copy来说,两个是完全独立的,改变任意一个元素(无论是多少层),另一个不会随着改变。
import copy
just = ['eric','bob',34,'ida']
dep = ['helo','welcome','jams']
just.append(dep)
jesp = copy.deepcopy(just)
just[1] = 'tom'
jesp[4][0] = 'hi' print(just,id(just))
print(jesp,id(jesp)) ['eric', 'tom', 34, 'ida', ['helo', 'welcome', 'jams']] 43071752
['eric', 'bob', 34, 'ida', ['hi', 'welcome', 'jams']] 43348872
最新文章
- Lua BehaviourTree 各节点说明
- javaScript获取url中的参数
- JavaScript基础之DOM修改样式
- js数组操作【转载】
- shell 使用for循环 启动后台任务
- SUSE Linux 防火墙设置
- 小结 javascript中的类型检测
- C#泛型集合之Dictionary<;k, v>;使用技巧
- shell(1)
- jQuery常用技巧大放送
- 浩哥解析MyBatis源码(五)——DataSource数据源模块之非池型数据源
- js的深层克隆和浅层克隆代码和理解
- Python 练习: 打印0到99小于50或大于70的数字
- video自动禁止全屏
- python中datetime与string的相互转换
- 线路板(PCB)制作流程中英文对照表
- Numpy知识(一)
- whatweb工具
- [UVa10296]Jogging Trails
- 如何申请iOS开发者证书/发布app到手机