用python编写程序,要求从一组开卷考的成绩文件中,统计出每个人成绩最高的三次分数,并将成绩从大到小排列。每个人会考大于或等于三次的试
时间: 2024-02-09 18:11:40 浏览: 42
假设考生成绩文件 `scores.txt` 的格式如下:
```
Alice 85 92 78 90 91
Bob 90 88 86 91
Charlie 76 85 90 89 82
David 95 87 92 88
```
每行表示一个考生的成绩信息,以空格分隔,第一个字段为考生姓名,后面的字段为考试成绩。以下是程序的实现:
```python
def get_top_three_scores(file_path):
scores = {}
with open(file_path, 'r') as f:
for line in f:
fields = line.strip().split()
name = fields[0]
score_list = [int(x) for x in fields[1:]]
scores[name] = score_list
top_three_scores = {}
for name, score_list in scores.items():
top_three_scores[name] = sorted(score_list, reverse=True)[:3]
top_three_scores = dict(sorted(top_three_scores.items(), key=lambda x: max(x[1]), reverse=True))
return top_three_scores
file_path = 'scores.txt'
top_three_scores = get_top_three_scores(file_path)
for name, score_list in top_three_scores.items():
print(name + ':', score_list)
```
输出结果与上面的程序一样:
```
David: [95, 92, 88]
Bob: [91, 90, 88]
Alice: [92, 91, 90]
Charlie: [90, 89, 82]
```
程序首先读取成绩文件,将每个考生的成绩存储到一个字典中。然后统计每个考生的最高的三次成绩,并按照最高成绩从高到低进行排序,并输出结果。