list(chain)返回的浅表副本
chain,它等效于
chain[:]。
如果您想要列表的浅表副本,请使用
list(),它有时还用于从迭代器获取所有值。
y = list(x)和之间的区别
y = x:
浅拷贝:
>>> x = [1,2,3]>>> y = x #this simply creates a new referece to the same list object>>> y is xTrue>>> y.append(4) # appending to y, will affect x as well>>> x,y([1, 2, 3, 4], [1, 2, 3, 4]) #both are changed#shallow copy >>> x = [1,2,3] >>> y = list(x) #y is a shallow copy of x>>> x is y False>>> y.append(4) #appending to y won't affect x and vice-versa>>> x,y([1, 2, 3], [1, 2, 3, 4]) #x is still same
深度复制:
请注意,如果
x包含可变对象,则仅
list()或
[:]不足:
>>> x = [[1,2],[3,4]]>>> y = list(x) #outer list is different>>> x is y False
但是内部对象仍然是x中对象的引用:
>>> x[0] is y[0], x[1] is y[1] (True, True)>>> y[0].append('foo') #modify an inner list>>> x,y #changes can be seen in both lists([[1, 2, 'foo'], [3, 4]], [[1, 2, 'foo'], [3, 4]])
由于外部列表不同,因此修改x不会影响y,反之亦然
>>> x.append('bar')>>> x,y([[1, 2, 'foo'], [3, 4], 'bar'], [[1, 2, 'foo'], [3, 4]])
为了处理这个使用
copy.deepcopy。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)