我一直试图获得每个名称(键)的平均得分(值)输出,不幸的是由于是python的新手我无法在我的代码中成功实现avg
函数; /我想知道如何计算具有多重值的每个键的平均值,例如:
Rob: 3,5,2,7
Matt: 9,2,3,4
Dan: 5,6,3,1
此外,我计算了如何按照平均分数从最高到最低的顺序打印键。我是否必须将计算出的平均值输入到列表中,还是有不同的方式?
到目前为止,这是我的代码:
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])))
答案 0 :(得分:1)
使用python3.4,您可以使用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] = scores
已创建名称和所有分数列表的键/值配对。如果你可能有重复的名字,你需要先使用setdefault或更好,但使用defaultdict。
使用sorted(score_dict.keys())
也是不必要的,效率也低于sorted(score_dict)
。
或者只计算一次平均值并使用itemgetter作为排序的关键:
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))
答案 1 :(得分:0)
def avg_score(marks):
return float(sum(marks))/len(marks)
players = score_dict.items()
players.sort(key = lambda player: avg_score(player[1]), reverse=True)
for name, marks in players:
print("{} Scored: {}".format(name, avg_score(marks)))
答案 2 :(得分:0)
使用sum
和len
的简单解决方案可能是(我假设您正确地从文件中获取值并且可以获得字典): -
lables = {'Rob':[3,5,2,7], 'Matt':[9,2,3,4], 'Dan':[5,6,3,1]}
avg_list = [(key, float(sum(l))/len(l)) for key, l in lables.items()]
print avg_list #[('Rob', 4.25), ('Dan', 3.75), ('Matt', 4.5)]
avg_list_sorted = sorted(avg_list, key = lambda avg_tuple: avg_tuple[1], reverse=True)
print avg_list_sorted #[('Matt', 4.5), ('Rob', 4.25), ('Dan', 3.75)]
print [avg_tuple[0] for avg_tuple in avg_list_sorted] #['Matt', 'Rob', 'Dan']