首页 > 解决方案 > 你如何在python中显示来自外部文件的最高平均分排序的平均分数和名称,知道同一个名字可以出现多次?

问题描述

我已经在一个外部文件中记录了学生的姓名和分数,现在我想按最高平均数排序显示它们。但问题是一个学生可以参加 2、3 和 4 次测验,并有 4 个不同的分数。每个详细信息都记录在一个新行中,因此同一个学生可以有多个记录。你如何告诉系统只选择一次学生的名字但计算他/她的平均分数并显示它?

这是我按字母顺序显示文件内容时得到的。

Abidjan Danane scored 8
Abidjan Danane scores 9
Babell Zoro scored 8
Babell Zoro scored 8
Baby Toba scores 7
Baby Toba scored 9
Catarase Betty scored 8
Catarase Betty scored 9


scores = []
with open(ClassName) as f:          
    for line in f:                  
        user_score = line.split()   #splits line on each space
        scores.append([int(user_score[3]), user_score[0]])
    print(sorted(scores, reverse = True))


Abidjan Danane has an average score of 8.5
Babell Zoro has an average score of 8.0
Baby Toba has an average score of 8.0
Catarase Betty has an average score of 8.5

标签: python-3.x

解决方案


这是一个简单的选择:

import re
from collections import defaultdict
from statistics import mean

name_scores = defaultdict(list)

with open(ClassName) as file:
    for line in file:
        # split the line at 'scores' or 'scored'
        name, score = re.split(' score[sd] ', line)
        name_scores[name].append(int(score)) 

# name_scores = defaultdict(<class 'list'>, 
#   {'Abidjan Danane': [8, 9], 'Babell Zoro': [8, 8], 
#    'Baby Toba': [7, 9], 'Catarase Betty': [8, 9]})

for name, scores in sorted(name_scores.items()):
    score = mean(scores)
    print(f'{name:20s} {score:2.1f}')

推荐阅读