Python浅拷贝与深拷贝
#苦行僧 人气:0对列表深拷贝就是无论怎样改动新列表(单维or多维),原列表都不变。
而下面的浅拷贝,对于多维列表,只是第一维深拷贝了(嵌套的List保存的是地址,复制过去的时候是把地址复制过去了),所以说其内层的list元素改变了,原列表也会变。
一、浅拷贝(均是只对第一层进行深拷贝)
1. for循环依次赋值
old = [1, [1, 2, 3], 3] new = [] for i in range(len(old)): new.append(old[i]) new[0] = 3 new[1][0] = 3 print(old) print(new) ''' [1, [3, 2, 3], 3] [3, [3, 2, 3], 3] '''
2. 使用copy()函数
old = [1,[1,2,3],3] new = old.copy() new[0] = 3 new[1][0] =3 print(old) print(new)
输出:
[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
3. 使用列表生成式
old = [1,[1,2,3],3] new = [i for i in old] new[0] = 3 new[1][0] = 3 print(old) print(new)
输出:
[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
4. 使用索引 [:]
old = [1,[1,2,3],3] new = old[:] new[0] = 3 new[1][0] = 3 print(old) print(new)
输出:
[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
浅拷贝对于单层列表就是深拷贝,如:
old = [1,2,3] new = old[:] new[0] = 666 print(old) print(new) """ [1, 2, 3] [666, 2, 3] """
二、深拷贝
使用用deepcopy()方法,才是真正的复制了一个全新的和原列表无关的:
import copy old = [1,[1,2,3],3] new = copy.deepcopy(old) new[0] = 3 new[1][0] = 3 """ [1, [1, 2, 3], 3] [3, [3, 2, 3], 3] """
加载全部内容