Python - 字典中各个键的每个值的平均值

标签 python loops dictionary

<分区>

我在遍历整个字典以对跨键的值的每个元素进行简单的汇总统计(平均)时遇到问题。

我的字典由作为数字列表的键和值组成:

test_dict={'NJ':[20,50,70,90,100],'NY':[10,3,0,99,57],'CT':[90,1000,2,3.4,5]}

我知道我可以访问每个键的第一个值,例如,通过执行以下操作,但我在明显的下一步添加另一个 for 循环以遍历值中的所有元素时遇到了麻烦。

location1=[element[0] for element in test_dict.values()] 
location1_avg=sum(location1)/len(location1)

我的最终目标是拥有一个以标签作为键(位置 1...i)和该位置各州的平均值的字典。因此,第一个键值将是 Location1: 40,依此类推。

我进行了以下尝试,但错误消息是“列表索引超出范围”,在这种情况下我不知道如何正确迭代。

for element in test_dict.values():
    avg=list()
    for nums in element[i]:
        avg[i]=sum(element[i][nums])/len(element[i][nums])

为每个请求添加所需的输出

soln_dict={'Location1':40,'Location2':351,'Loction3':24,'Loction4':43.24,'Loction5':54}

感谢您的帮助!

最佳答案

只是做:

#loop through the dictionary
for key,value in test_dict.items(): 

   #use reduce to calculate the avg
   print(key, reduce(lambda x, y: x + y, test_dict[key]) / len(test_dict[key]))

这将打印:

NJ 66.0
NY 33.8
CT 220.08

编辑:根据 OP 要求的变化:

l = list(iter(test_dict.values()))                      #convert values to list
print(l)
#[[20, 50, 70, 90, 100], [10, 3, 0, 99, 57], [90, 1000, 2, 3.4, 5]]
d={}                                                                  #final ditionary
for i in range(len(l[0])): 
   row_list = [row[i] for row in l]                     #get values column-wise
   d['location'+str(i+1)] = sum(row_list)/len(row_list)               #calculate avg

print(d)
#{'location1': 40.0, 'location2': 351.0, 'location3': 24.0, 'location4': 64.13333333333334, 'location5': 54.0}

注意:您为 loaction4 提出的平均值是错误的。

关于Python - 字典中各个键的每个值的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46382525/

相关文章:

dictionary - 我怎样才能在groovy中进行有条件的collectEntries

java - 使用 for-each 循环和 Map.Entry() 删除 LinkedHashMap 实例中等于字符串 "world"的任何键值,但总是出错

python - 应要求 flask 挂起

python - 如何从 URL 不变的网页中抓取 pdf 链接?

python - 在 pyqt 中显示运行时输出

可选参数验证的python可选参数

Java方法专门检查数组是否有重复四次的元素

python - 使用循环中的新项目将列表与另一个列表进行标识

c# - 计算一段时间内每小时的分钟数

ios - 在 TableView 中填充数组字典的高效且干净的方法