繁体   English   中英

字典词典内的列表未正确附加值

[英]A List inside of a Dictionary of Dictionaries is not appending values correctly

我正在做一个预测股票价格的大型项目,它包括嵌套在另一个字典中的字典中的整数列表。 有点疑惑:)

问题是,每当我尝试将一个列表的值设为不同的 integer 时,它都会为整个列表字典执行此操作。 我将包含一个示例代码和下面的问题

for k,v in equities_and_value.items():
    stocks_and_runs_total_dictionary[k]={0 : [v]}
for i in stocks_and_runs_total_dictionary:
    for x in range(0,runs): 
        stocks_and_runs_total_dictionary[i][x] = stocks_and_runs_total_dictionary[i][0]
    for y in range(0, years):
        stocks_and_runs_total_dictionary[i][y].append(0)
            

stocks_and_runs_total_dictionary["IBM"][0][1] = 500

添加 500 之前的stocks_and_runs_total_dictionary 的值:

{'IBM': {0: [600, 0, 0], 1: [600, 0, 0], 2: [600, 0, 0]}, 'MS': {0: [600, 0, 0], 1: [600, 0, 0], 2: [600, 0, 0]}, 'PEP': {0: [600, 0, 0], 1: [600, 0, 0], 2: [600, 0, 0]}}

添加 500 后的stocks_and_runs_total_dictionary 的值:

{'IBM': {0: [600, 500, 0], 1: [600, 500, 0], 2: [600, 500, 0]}, 'MS': {0: [600, 0, 0], 1: [600, 0, 0], 2: [600, 0, 0]}, 'PEP': {0: [600, 0, 0], 1: [600, 0, 0], 2: [600, 0, 0]}}

我希望通过代码获得的价值:

{'IBM': {0: [600, 500, 0], 1: [600, 0, 0], 2: [600, 0, 0]}, 'MS': {0: [600, 0, 0], 1: [600, 0, 0], 2: [600, 0, 0]}, 'PEP': {0: [600, 0, 0], 1: [600, 0, 0], 2: [600, 0, 0]}}

我认为这可能与列表是一个 object 的引用而不是单独的变量有关,因为这是解决类似问题的方法。 这段代码就是这么多嵌套循环,答案让我感到困惑,所以我在这里寻求帮助

有什么解决办法吗? 谢谢!

当您编写stocks_and_runs_total_dictionary[i][x] = stocks_and_runs_total_dictionary[i][0]时,这不会复制列表。 它使每个列表指向存储原始列表的相同 memory 地址。因此,当您更改一个列表时,您将同时更改指向同一 memory 地址的所有位置的列表。 这就是为什么所有 arrays 的[1]索引都更改为 500。

一种解决方法是创建列表的硬拷贝并将其重新分配给stocks_and_runs_total_dictionary["IBM"][0]

a = {'IBM': {0: [600, 0, 0], 1: [600, 0, 0], 2: [600, 0, 0]}, 'MS': {0: [600, 0, 0], 1: [600, 0, 0], 2: [600, 0, 0]}, 'PEP': {0: [600, 0, 0], 1: [600, 0, 0], 2: [600, 0, 0]}}`

copyDesiredList = list(a['IBM'][0])
copyDesiredList[1] = 500
a['IBM'][0] = copyDesiredList

这将返回您想要的 output。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM