首页 > 解决方案 > 从另一个数组初始化数组

问题描述

我怎样才能以正确的方式做到这一点?

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

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

标签: python

解决方案


重复引用(指向同一个列表):

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)

推荐阅读