替换存储在字典中的特定 numpy 数组中的条目

Replace entry in specific numpy array stored in dictionary

我有一个字典,其中包含可变数量的 numpy 数组(长度都相同),每个数组都存储在其各自的键中。

对于每个索引,我想用新计算的值替换其中一个数组中的值。 (这是我实际正在做的一个非常简单的版本。)

问题是,当我尝试如下所示时,字典中每个数组的当前索引处的值都被替换,而不仅仅是我指定的那个。

抱歉,如果示例代码的格式令人困惑,这是我的第一个问题(不太明白如何在 for 循环的下一行中正确显示 example_dict["key1"][idx] = idx+10 行...... ).

>>> import numpy as np 

>>> example_dict = dict.fromkeys(["key1", "key2"], np.array(range(10)))

>>> example_dict["key1"]

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> example_dict["key2"]

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> for idx in range(10):
    example_dict["key1"][idx] = idx+10



>>> example_dict["key1"]

array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

>>> example_dict["key2"]

array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

我希望循环只访问 example_dict["key1"] 中的数组,但不知何故同样的操作也应用于 example_dict["key2"] 中存储的数组。

>>> hex(id(example_dict["key1"]))
'0x26a543ea990'
>>> hex(id(example_dict["key2"]))
'0x26a543ea990'

example_dict["key1"]example_dict["key2"] 指向同一个地址。要解决此问题,您可以使用字典理解。

import numpy
keys = ["key1", "key2"]
example_dict = {key: numpy.array(range(10)) for key in keys}