如何正确执行此操作?
a = ['1','2']
b = []
for value in a:
b.append(value)
我需要这样做,因为我想更改a中的值,但我想将其保留在b中。
当我做b = a
时,似乎只是将指针设置为a中的值。
答案 0 :(得分:2)
重复引用(指向相同列表):
b = a
软拷贝(所有相同的元素,但列表不同):
b = a[:] # special version of the slice notation that produces a softcopy
b = list(a) # the list() constructor takes an iterable. It can create a new list from an existing list
b = a.copy() # the built-in collections classes have this method that produces a soft copy
对于深层副本(所有元素的副本,而不仅仅是相同的元素),您需要调用内置的copy
模块。
from copy import deepcopy
b = deepcopy(a)
答案 1 :(得分:1)
您可以使用:
b = a[:]
答案 2 :(得分:0)
您可以使用以下内容将一个列表复制到另一个列表。
b = a.copy()