文件studentscore.txt包含了学生在期末考试中的成绩。编写一段程序,根据分数进行升序排序后,输出学生的数量,成绩的最低分和最高分,成绩为前n名和后n名的同学姓名(n为非负数,当n大于数据行数时,按实际行数输出),以及平均成绩(保留小数点后2位)。
时间: 2024-01-02 18:04:06 浏览: 21
好的,我可以帮您写一个Python程序来解决这个问题。请确保您已经安装了Python并拥有文件studentscore.txt。
以下是程序代码:
```python
# 打开文件并读取数据
with open('studentscore.txt', 'r') as f:
data = f.readlines()
# 将数据转换为字典
scores = {}
for line in data:
name, score = line.strip().split()
scores[name] = int(score)
# 对字典进行排序
sorted_scores = sorted(scores.items(), key=lambda x: x[1])
# 计算并输出结果
num_students = len(sorted_scores)
min_score = sorted_scores[0][1]
max_score = sorted_scores[-1][1]
average_score = sum(scores.values()) / num_students
print("学生数量:", num_students)
print("最低分:", min_score)
print("最高分:", max_score)
print("平均分:{:.2f}".format(average_score))
n = int(input("输入前n名和后n名的同学姓名:"))
if n > num_students:
n = num_students
top_n = sorted_scores[-n:]
bottom_n = sorted_scores[:n]
print("前{}名同学:".format(n))
for name, score in top_n:
print(name)
print("后{}名同学:".format(n))
for name, score in bottom_n:
print(name)
```
这个程序将打开文件并读取数据,然后将数据转换成一个字典。接下来,使用Python的sorted函数对字典进行排序,并计算出最低分、最高分、学生数量、平均成绩等信息。最后,程序会要求您输入需要输出的前n名和后n名同学的姓名,并输出这些同学的姓名。
请确保在程序运行时,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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)