python的深拷贝和浅拷贝,以list为例

训练的时候遇到个大坑,就是深拷贝浅拷贝的问题,模型直接训错了,记录一下警示自己。

参考https://www.cnblogs.com/Black-rainbow/p/9577029.html

在验证代码时,发现了一个问题,就是切片赋值跟上述博文结果不符,原因未知。请知道原因的小伙伴不吝赐教。

深拷贝的方法是使用copy.deepcopy。其他方法为浅拷贝,除了切片赋值。测试代码在python3.6上运行。

样例:

深拷贝

import copy
old = [1,[1,2,3],3]
new = copy.deepcopy(old)
print('Before:', old, new)
new[0] = 3
new[1][0] = 3
print('After:', old, new)
Before: [1, [1, 2, 3], 3] [1, [1, 2, 3], 3]
After: [1, [1, 2, 3], 3] [3, [3, 2, 3], 3]

浅拷贝

1.=赋值

old = [1,[1,2,3],3]
new = old
print('Before:', old, new)
new[0] = 3
new[1][0] = 3
print('After:', old, new)
Before: [1, [1, 2, 3], 3] [1, [1, 2, 3], 3]
After: [3, [3, 2, 3], 3] [3, [3, 2, 3], 3]

2.copy()

old = [1,[1,2,3],3]
new = old.copy()
print('Before:', old, new)
new[0] = 3
new[1][0] = 3
print('After:', old, new)
Before: [1, [1, 2, 3], 3] [1, [1, 2, 3], 3]
After: [3, [3, 2, 3], 3] [3, [3, 2, 3], 3]

3.使用列表生成

old = [1,[1,2,3],3]
new = [i for i in old]
print('Before:', old, new)
new[0] = 3
new[1][0] = 3
print('After:', old, new)
Before: [1, [1, 2, 3], 3] [1, [1, 2, 3], 3]
After: [3, [3, 2, 3], 3] [3, [3, 2, 3], 3]

4.用for循环遍历

old = [1,[1,2,3],3]
new = []
for i in range(len(old)):
    new.append(old[i])
print('Before:', old, new)
new[0] = 3
new[1][0] = 3
print('After:', old, new)
Before: [1, [1, 2, 3], 3] [1, [1, 2, 3], 3]
After: [3, [3, 2, 3], 3] [3, [3, 2, 3], 3]

5.使用切片?

old = [1,[1,2,3],3]
new = old[:]
print('Before:', old, new)
new[0] = 3
new[1][0] = 3
print('After:', old, new)

 注意:此处old[0]的值没变,old[1][0]的值变了。

Before: [1, [1, 2, 3], 3] [1, [1, 2, 3], 3]
After: [1, [3, 2, 3], 3] [3, [3, 2, 3], 3]

然后我又做了个测试

old = [1,2,3]
new = old[:]
print('Before:', old, new)
new[0] = 3
print('After:', old, new)

 深拷贝?

Before: [1, 2, 3] [1, 2, 3]
After: [1, 2, 3] [3, 2, 3]

没弄明白切片是深拷贝还是浅拷贝。没弄清楚前暂时不用这个方法了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值