python列表深浅拷贝

1、浅拷贝
对于浅copy来说,第一层创建的是新的内存地址,而从第二层开始,指向的都是同一个内存地址,所以,对于第二层以及更深的层数来说,保持一致性。

list1 = [1, 2, 3, ['tom', 'jerry']]
list2 = list1.copy()

# 两个列表首地址不同,如:
print(list1, id(list1))  # [1, 2, 3, ['tom', 'jerry']] 18228552
print(list2, id(list2))  # [1, 2, 3, ['tom', 'jerry']] 18244168

# list2中的1,2,3是新的内存地址,改变list1时,对list2无影响,如:
list1[1] = 222
print(list1, id(list1))  # [1, 222, 3, ['tom', 'jerry']] 18228552
print(list2, id(list2))  # [1, 2, 3, ['tom', 'jerry']] 18244168

# (浅拷贝)第二层列表是同一地址,没有在拷贝时开辟新空间,两个二层列表共处一室
list1[3][0] = 'blue'
print(list1, id(list1[3]))  # [1, 222, 3, ['blue', 'jerry']] 18230984
print(list2, id(list2[3]))  # [1, 2, 3, ['blue', 'jerry']] 18230984

2、深拷贝(仅第三个注释中发生改变)
(1)需要导入 copy 模块。
Import copy

(2)运用copy.deepcopy()

代码:

import copy
list1 = [1, 2, 3, ['tom', 'jerry']]
list2 = copy.deepcopy(list1)

# 深度拷贝后首地址也不同,如:
print(list1, id(list1))  # [1, 2, 3, ['tom', 'jerry']] 19160776
print(list2, id(list2))  # [1, 2, 3, ['tom', 'jerry']] 19116296

# list2中的1, 2, 3也是新的内存地址,改变list1时,对list2也无影响,如:
list1[1] = 222
print(list1, id(list1))  # [1, 222, 3, ['tom', 'jerry']] 19160776
print(list2, id(list2))  # [1, 2, 3, ['tom', 'jerry']] 19116296

# 仅此处不一样,深度拷贝的第二层地址也不一样,不是指向同一地址块,两个第二层列表独立!
list1[3][0] = 'blue'
print(list1, id(list1[3]))  # [1, 222, 3, ['blue', 'jerry']] 19117768
print(list2, id(list2[3]))  # [1, 2, 3, ['tom', 'jerry']] 19117832
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值