文件studentscore.txt包含了学生在期末考试中的成绩。编写一段程序,根据分数进行升序排序后,输出学生的数量,成绩的最低分和最高分,成绩为前n名和后n名的同学姓名(n为非负数,当n大于数据行数时,按实际行数输出),以及平均成绩(保留小数点后2位)。
时间: 2024-01-02 22:04:20 浏览: 12
好的,以下是一份Python代码,可以实现您的需求:
```python
# 读取文件
with open('studentscore.txt', 'r') as f:
lines = f.readlines()
# 去除每行末尾的换行符,并转换成列表
scores = [line.strip().split() for line in lines]
# 将分数转换成浮点数
scores = [[name, float(score)] for name, score in scores]
# 按分数升序排序
scores.sort(key=lambda x: x[1])
# 学生数量
num_students = len(scores)
# 最低分和最高分
min_score = scores[0][1]
max_score = scores[-1][1]
# 前n名和后n名
n = 3 # 假设n为3
n = min(n, num_students) # n不能超过学生数量
top_n = scores[:n]
bottom_n = scores[-n:]
# 平均成绩
avg_score = sum(score for _, score in scores) / num_students
# 输出结果
print("学生数量:", num_students)
print("最低分:", min_score)
print("最高分:", max_score)
print("前{}名:".format(n))
for name, _ in top_n:
print(name)
print("后{}名:".format(n))
for name, _ in bottom_n:
print(name)
print("平均成绩:{:.2f}".format(avg_score))
```
您可以将上述代码保存到一个Python文件中,然后将`studentscore.txt`文件放在同一目录下,运行代码即可得到结果。当然,您也可以根据实际情况修改代码中的一些参数和细节。
相关推荐
![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)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)