【问题标题】:Highest to Lowest from an average从平均最高到最低
【发布时间】:2016-08-26 11:40:58
【问题描述】:

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

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)

...到平均sn-p结束。我尝试了几种不同的方法,没有任何继承。一旦程序的平均部分完成,它就会返回这些,这就是我需要排序的。

Derek 4.0
Fred 9.0
George 7.0
Jake 3.6666666666666665

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

【问题讨论】:

  • 你为什么要排序entries?这没有任何意义。此外,您应该考虑使用预期输出显示文件内容示例。
  • 我正在尝试将现在平均的分数从高到低排序
  • 您似乎知道如何对列表进行排序,因此不仅要将分数打印到输出中,还可以使用.append() 将它们添加到列表中。然后对该列表进行排序。

标签: python sorting csv average


【解决方案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)

【讨论】:

  • 在 Python3 中你可以使用 averages.least_common(n) 而不是 averages.most_common()[:-n-1:-1]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
  • 2012-10-16
  • 1970-01-01
  • 1970-01-01
  • 2016-06-04
  • 1970-01-01
相关资源
最近更新 更多