从平均值到最高到最低

时间:2016-05-01 18:01:46

标签: python sorting csv average

我目前有一段代码可以从文件中找到平均值,到目前为止我可以找到平均值,但之后无法对其进行排序,下面是我找到平均值的代码:

path = 'team1scores.csv'
with open(path) as f:
    entries = collections.Counter()
    total_scores = collections.Counter()
    for name,score in csv.reader(f):
        score = int(score)
        total_scores[name] += score
        entries[name] += 1

    for name in sorted(entries):
        ave_score = total_scores[name] / entries[name]
        print(name,ave_score)

在同一个程序中,我在另一个点使用了从最高到最低的排序,所以我能以某种方式添加这个...

path = 'team1cores.csv'
    with open(path) as f:
        entries = sorted(csv.reader(f), key=itemgetter(1), reverse=True)
    for name,score in entries:
        print(name,score)

...到平均片段的末尾。我已经尝试了几种不同的方式而没有任何继承。一旦程序的平均部分完成,它就会返回这些,这就是我需要排序的东西。

Derek 4.0
Fred 9.0
George 7.0
Jake 3.6666666666666665

希望这是一个简单的问题。

1 个答案:

答案 0 :(得分:1)

您应该更好地考虑代码的结构:对文件读取过程进行排序没有意义......如果要对平均分数进行排序,则必须在特定变量中注册此信息。

我相信你想做这样的事情:

path = 'team1scores.csv'

entries = collections.Counter()
total_scores = collections.Counter()

with open(path) as f:
    for name,score in csv.reader(f):
        score = int(score)
        total_scores[name] += score
        entries[name] += 1

averages = collections.Counter()
for name in entries.keys():
    averages[name] = total_scores[name]/entries[name]

# `most_common(n)` will display the sorted `n` highest values
for name, score in averages.most_common():
    print(name, score)

# to sort the `n` from lowest, used most_common()[:`-n-1`:-1]
n = 2
for name, score in averages.most_common()[:-n-1:-1]:
    print(name, score)