从另一个数组初始化数组

时间:2020-04-02 15:19:18

标签: python

如何正确执行此操作?

a = ['1','2']
b = []
for value in a:
    b.append(value)

我需要这样做,因为我想更改a中的值,但我想将其保留在b中。 当我做b = a时,似乎只是将指针设置为a中的值。

3 个答案:

答案 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()
相关问题