多个字典中的平均值?

2024-10-01 00:17:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有4个字典,其中symbol作为键,LTP作为值。现在我想创建一个新的字典,其中symbol作为我的键,4字典的LTP的平均值作为我的值

first = {"MRF":40000,"RELIANCE":1000}
second = {"MRF":50000,"RELIANCE":2000}
third = {"MRF":30000,"RELIANCE":500}
fourth = {"MRF":60000,"RELIANCE":4000}

new = {"MRF":45000,"RELIANCE":1875}  # this is the average of ltp

请帮我想个办法好吗


Tags: thenew字典isthissymbol平均值first
2条回答

我们可以使用统计库和列表理解中的均值方法得到这个结果

代码如下:

注意:假设所有字典中的键都相同:

注意:我将Python3.x用于以下代码:

from statistics import mean 

first = {"MRF":40000,"RELIANCE":1000}
second = {"MRF":50000,"RELIANCE":2000}
third = {"MRF":30000,"RELIANCE":500}
fourth = {"MRF":60000,"RELIANCE":4000}

dictionaryList = [first,second,third,fourth]
new = {}

for key in first.keys():
    new[key] = mean([d[key] for d in dictionaryList ])
print(new)

它会产生与您所需完全相同的结果

{'MRF': 45000, 'RELIANCE': 1875}

first = {"MRF":40000,"RELIANCE":1000}
second = {"MRF":50000,"RELIANCE":2000}
third = {"MRF":30000,"RELIANCE":500}
fourth = {"MRF":60000,"RELIANCE":4000}

dicts = [first, second, third, fourth]
keys = first.keys()
new = {k: sum((d[k] for d in dicts)) / len(dicts) for k in first.keys()}
print(new) ## {'MRF': 45000.0, 'RELIANCE': 1875.0}

相关问题 更多 >