python-3.x - 你如何在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
解决方案
这是一个简单的选择:
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}')
推荐阅读
- javascript - JavaScript 老虎机:选择获胜者的简单算法是什么?
- angular - 我想在 ionic 4 页面之间传递数据
- android - 使用日期选择器和当前日期查找天数
- google-apps-script - 如果 O2 值更新,那么我需要使用模板向 C2 中的地址发送电子邮件。如果单元格 O2 已更新,则电子邮件应仅发送至 C2
- apache-kafka-streams - 如何使用相同的 APPLICATION_ID_CONFIG 运行两个或多个拓扑?
- http - Http POST 请求以 base64 编码的 json 形式返回正文
- javascript - 如何在控制台中打印值而不传递任何函数?
- maven - Maven给出编译错误:引用的jar包不存在
- python - 如何裁剪轮廓的内部?
- python - 使用 Windows CMD 从下载的文件夹安装依赖项