我使用python数组已有一段时间了,但是最近我遇到了一个奇怪的问题。这是我的代码:
import numpy as np
myarr = [
["s"],
["s"],
["w"],
["p"],
["m"],
["g"],
["c"]
]
newarr = list(myarr)
print(id(myarr))
print(id(newarr))
print(myarr, "myarr")
print(newarr, "newarr")
print("##### starting manipulation #########")
for i in newarr:
i[0] = "a"
print(myarr, "myarr")
print(newarr, "newarr")
我的问题是,甚至当我将“ myarr”数组复制到名为“ newarr”的新数组中时,当我对“ myarr”或“ newarr”进行一些更改时,它们两者的行为都类似于引用数组(引用到相同的内存地址),即使它们具有不同的内存ID。
我尝试了切片,甚至使用了arr.copy()方法,但是它们都不起作用。
我只能在使用numpy数组时修复它。
newarr = np.array(myarr)
我的问题在哪里?
提前谢谢:)
答案 0 :(得分:1)
您需要使用deepcopy
from copy import deepcopy
myarr = [
["s"],
["s"],
["w"],
["p"],
["m"],
["g"],
["c"]
]
newarr = deepcopy(myarr)
print(myarr, "myarr")
print(newarr, "newarr")
print("##### starting manipulation #########")
for i in newarr:
i[0] = "a"
print(myarr, "myarr")
print(newarr, "newarr")
输出:
([['s'], ['s'], ['w'], ['p'], ['m'], ['g'], ['c']], 'myarr')
([['s'], ['s'], ['w'], ['p'], ['m'], ['g'], ['c']], 'newarr')
##### starting manipulation #########
([['s'], ['s'], ['w'], ['p'], ['m'], ['g'], ['c']], 'myarr')
([['a'], ['a'], ['a'], ['a'], ['a'], ['a'], ['a']], 'newarr')