python - 从另一个数组初始化数组
问题描述
我怎样才能以正确的方式做到这一点?
a = ['1','2']
b = []
for value in a:
b.append(value)
我需要这样做,因为我想更改 a 中的值,但我想将它们保留在 b 中。当我这样做时b = a
,它似乎只是将指针设置为 a.
解决方案
重复引用(指向同一个列表):
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)
推荐阅读
- python - 我应该从更标准的数学库中重载 sin(x) 还是开发自己的类方法 sin?
- azure - Azure AD B2C 自定义域
- java - 如何在 100 秒后或调用一次后将字符串值返回为 null?
- angularjs - 是否有任何简单直接的方法来模拟\测试 MSAL JS $rootScope.$on("msal:acquireTokenFailure") 事件?
- c# - C# XmlReader 非常慢
- python - 使用python从多个同名的选择框中进行选择
- asp.net-web-api - Web api 应用程序中 go daddy 的内部服务器错误
- python - 如何将 Pandas 数据框中的列分隔为唯一的箱/列?
- android - JSON 数据未显示在 Recylerview MVVM 中
- c# - 依赖于 System.ComponentModel.Annotations 的 .Net Standard 2.0 Nuget 包仅在从 .Net Framework 项目中使用时才会引发异常