训练的时候遇到个大坑,就是深拷贝浅拷贝的问题,模型直接训错了,记录一下警示自己。
参考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]
没弄明白切片是深拷贝还是浅拷贝。没弄清楚前暂时不用这个方法了。