Python3 复制和深浅copy
赋值:
列表的赋值:
1 list1 = ['peter','sam'] 2 list2 = list1 3 4 print(list1,id(list1)) 5 print(list2,id(list2)) 6 list1.append('hery') 7 print(list1,id(list1)) 8 print(list2,id(list2)) 9 10 ['peter', 'sam'] 5071496 11 ['peter', 'sam'] 5071496 12 ['peter', 'sam', 'hery'] 5071496 13 ['peter', 'sam', 'hery'] 5071496
字典的赋值:

1 dic = {'name':'just'} 2 dic1 = dic 3 4 print(dic,id(dic)) 5 print(dic1,id(dic1)) 6 7 dic['age'] = 27 8 9 print(dic,id(dic)) 10 print(dic1,id(dic1)) 11 12 13 14 15 {'name': 'just'} 38505064 16 {'name': 'just'} 38505064 17 {'name': 'just', 'age': 27} 38505064 18 {'name': 'just', 'age': 27} 38505064
字符串赋值:

1 str = 'hello' 2 str1 = str 3 4 print(str,id(str)) 5 print(str1,id(str1)) 6 7 str = str.replace('e','E') 8 9 print(str,id(str)) 10 print(str1,id(str1)) 11 12 13 14 hello 35026176 15 hello 35026176 16 hEllo 39638608 17 hello 35026176
创建两个相同的变量,他们的内存地址相同(以前版本好像是不同)

1 str = 'h' 2 str3 = 'h' 3 4 print(str,id(str)) 5 print(str3,id(str3)) 6 print( str is str3) 7 8 9 10 h 39056528 11 h 39056528 12 True
浅copy:
浅copy来说,第一层创建的是新的内存地址。而从第二层开始,指向的是同一个内存地址,所有,对于第二层以及更深的层数来说,保持一致性。

1 just = ['eric','bob',34,'ida'] 2 dep = ['helo','welcome','jams'] 3 jesp = just.copy() 4 5 print(just,id(just)) 6 print(jesp,id(jesp)) 7 8 9 10 ['eric', 'bob', 34, 'ida'] 37435528 11 ['eric', 'bob', 34, 'ida'] 37497480

1 just = ['eric','bob',34,'ida'] 2 dep = ['helo','welcome','jams'] 3 just.append(dep) 4 jesp = just.copy() 5 just[1] = 'tom' 6 jesp[4][0] = 'hi' 7 8 print(just,id(just)) 9 print(jesp,id(jesp)) 10 11 12 13 ['eric', 'tom', 34, 'ida', ['hi', 'welcome', 'jams']] 42744008 14 ['eric', 'bob', 34, 'ida', ['hi', 'welcome', 'jams']] 43021128
深copy:
对深copy来说,两个是完全独立的,改变任意一个元素(无论是多少层),另一个不会随着改变。
1 import copy 2 just = ['eric','bob',34,'ida'] 3 dep = ['helo','welcome','jams'] 4 just.append(dep) 5 jesp = copy.deepcopy(just) 6 just[1] = 'tom' 7 jesp[4][0] = 'hi' 8 9 print(just,id(just)) 10 print(jesp,id(jesp)) 11 12 13 14 ['eric', 'tom', 34, 'ida', ['helo', 'welcome', 'jams']] 43071752 15 ['eric', 'bob', 34, 'ida', ['hi', 'welcome', 'jams']] 43348872
o(=•ェ•=)m纸上得来终觉浅,绝知此事要躬行o(=•ェ•=)m
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构