如何找到密钥的多个值的平均值? [英] How to find an average of multiple values for a key?

查看:157
本文介绍了如何找到密钥的多个值的平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图获得每个名称(键)的平均分数(值)的输出,不幸的是由于新的python我无法实现 avg 函数在我的代码中成功; /我想知道如何计算每个具有多重值的键的平均值,如:

I've been trying to get an output of average score(value) for each name(key), unfortunately due to being new to python I was unable to implement the avg function within my code successfully ;/ I was wondering how could I calculate an average for each key which has multipile values such as :

Rob: 3,5,2,7
Matt: 9,2,3,4
Dan: 5,6,3,1

在计算之后,如何按平均分数按最高到最低的顺序打印密钥。我必须将计算的平均值输入到列表中,还是有不同的方式?

Also after calculating how would I be able to print the keys in order of average score, from highest to lowest. Would I have to input the calculated average into a list or is there a different way?

这是迄今为止的代码:

with open('score_file.txt') as infile:
    for line in infile:
        name_field, scores = line.split(':') 
        name = name_field.split()[0]        
        scores = [int(score.strip()) for score in scores.split(',')]


    score_dict[name] = scores
    score_dict.setdefault(name, []).extend(scores)


for name in sorted(score_dict.keys()):
    print("{} Scored: {}".format(name, avg(score_dict[name])))


推荐答案

使用python3.4可以使用 statistics.mean

Using python3.4 you can use statistics.mean:

from statistics import mean
for name,val in sorted(score_dict.items(),key=lambda x:mean(x[1])):
    print("{} Scored: {}".format(name, mean(val))


Dan Scored: 3.75
Rob Scored: 4.25
Matt Scored: 4.5

您还可以删除 score_dict.setdefault(name,[])。extend(scores) score_dict [name] = score 已经创建了名称和所有分数列表的键/值配对。如果你可能有重复的名字,你需要先使用setdefault或更好地使用defaultdict。

You can also remove the score_dict.setdefault(name, []).extend(scores),score_dict[name] = scores already creates a key/value pairing of the name and the list of all scores. If you might have repeated names you would need to use setdefault first or better yet use a defaultdict.

还使用 sorted(score_dict.keys() )是不必要的,效率更低,只需使用 sorted(score_dict)

Also using sorted(score_dict.keys()) is unnecessary and less efficient that just using sorted(score_dict).

或只需计算平均值一次,并使用itemgetter作为排序的关键:

Or just calculate the mean once and use itemgetter as the key to sorted:

from statistics import mean
from operator import itemgetter
srted_mean = ((k, mean(v)) for k, v in score_dict.items())
for name,mn in sorted(srted_mean,key=itemgetter(1)):
    print("{} Scored: {}".format(name, mn))

这篇关于如何找到密钥的多个值的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆