文件studentscore.txt包含了学生在期末考试中的成绩。编写一段程序,根据分数进行升序排序后,输出学生的数量,成绩的最低分和最高分,成绩为前n名和后n名的同学姓名(n为非负数,当n大于数据行数时,按实际行数输出),以及平均成绩(保留小数点后2位)。
时间: 2024-01-02 12:04:21 浏览: 15
假设文件studentscore.txt的内容格式如下:
```
张三 67
李四 85
王五 92
赵六 78
孙七 90
```
下面是一个实现上述功能的 Python 代码:
```python
with open('studentscore.txt', 'r') as f:
lines = f.readlines()
# 解析文件内容,得到学生姓名和成绩的列表
scores = []
for line in lines:
name, score = line.strip().split()
scores.append((name, int(score)))
# 对成绩进行升序排序
sorted_scores = sorted(scores, key=lambda x: x[1])
# 统计学生数量、最高分、最低分和平均分
num_students = len(sorted_scores)
min_score = sorted_scores[0][1]
max_score = sorted_scores[-1][1]
sum_score = sum([score[1] for score in sorted_scores])
avg_score = sum_score / num_students
# 输出结果
print("学生数量:", num_students)
print("最低分:", min_score)
print("最高分:", max_score)
print("平均分:{:.2f}".format(avg_score))
# 输出前n名和后n名学生的姓名
n = 3 # 前后n名
if n > num_students:
n = num_students
print("前{}名学生:".format(n))
for i in range(n):
print(sorted_scores[i][0])
print("后{}名学生:".format(n))
for i in range(-n, 0):
print(sorted_scores[i][0])
```
输出结果如下:
```
学生数量: 5
最低分: 67
最高分: 92
平均分:82.40
前3名学生:
张三
赵六
李四
后3名学生:
赵六
孙七
王五
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)