更新 python 数组时出现问题

问题描述 投票:0回答:1
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 arrays python-3.x
1个回答
1
投票

还有其他事情发生。 在 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'}]
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.