new = [{'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}]
我尝试仅使用
new[0]['indicator']='HMA'
更新上面的数组 0 元素,但在尝试打印时更新后会出现以下响应。
[{'n': '1234', 'indicator': 'HMA'}, {'n': '1234', 'indicator': 'HMA'}, {'n': '1234', 'indicator': 'HMA'}, {'n': '1234', 'indicator': 'HMA'}]
这里我试图只更新数组 0 元素,但它更新了所有 4 个元素。
请帮我解决问题
更新过程完成后,我需要以下回复
[{'n': '1234', 'indicator': 'HMA'}, {'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}]
还有其他事情发生。 在 Python 3.12.1 上,这就是我所看到的。
>>> new = [{'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}]
>>> new
[{'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}]
>>> new[0]['indicator']='HMA'
>>> new
[{'n': '1234', 'indicator': 'HMA'}, {'n': '1234', 'indicator': 'RSI'}]
>>>
>>>
这是因为你的原始代码中没有这个。 如果你创建一个项目x,然后将其添加到列表中三次,你将得到你所描述的效果。
>>> x = {'n': '1234', 'indicator': 'RSI'}
>>> new = [x,x,x]
>>> new
[{'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}]
>>> new[0]['indicator']='HMA'
>>> new
[{'n': '1234', 'indicator': 'HMA'}, {'n': '1234', 'indicator': 'HMA'}, {'n': '1234', 'indicator': 'HMA'}]
>>>
发生的情况是该列表由对 x 的三个引用组成,而不是对 x 的三个实例,并且在通过任何引用修改 x 时,该列表仍然存在..
我们可以使用copy()方法来实例化。
>>> x = {'n': '1234', 'indicator': 'RSI'}
>>> new = [x.copy(),x,x]
>>> new
[{'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}]
>>> new[0]['indicator']='HMA'
>>> new
[{'n': '1234', 'indicator': 'HMA'}, {'n': '1234', 'indicator': 'RSI'}, {'n': '1234', 'indicator': 'RSI'}]
>>>