繁体   English   中英

平均数从最高到最低

[英]Highest to Lowest from an 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

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

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM