This question already has answers here:
How to make a list of integers that is the sum of all the integers from a set of lists in a dict?
(2个答案)
2年前关闭。
我在遍历整个字典以对键中的值的每个元素进行简单的摘要统计(平均值)时遇到麻烦。
我的词典由数字列表组成的键和值组成:
我知道我可以访问每个键的第一个值,例如,通过执行以下操作,但是我在下一步添加另一个for循环以遍历值中的所有元素时遇到麻烦。
我的最终目标是拥有一个带有标签作为键的字典(位置1 ... i)以及该位置各州的平均值。因此,第一个键值将是Location1:40,依此类推。
我有以下尝试,但错误消息是“列表索引超出范围”,在这种情况下我不知道如何正确进行迭代。
为每个请求添加所需的输出
谢谢您的帮助!
这将打印:
编辑:根据OP要求的变化:
注意:您对loaction4提出的平均值是错误的。
(2个答案)
2年前关闭。
我在遍历整个字典以对键中的值的每个元素进行简单的摘要统计(平均值)时遇到麻烦。
我的词典由数字列表组成的键和值组成:
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提出的平均值是错误的。