有10个学生,每个学生的数据包括学号、姓名、3门功课的成绩。从键盘输入10个学生的数据,要求按平均成绩降序显示出所有学生的数据(包括学号、姓名、3门课成绩、平均成绩),并将其写入文本文件result.txt中。
时间: 2023-12-15 07:13:04 浏览: 21
好的,这是一个简单的学生成绩排序和写入文件的问题。以下是 Python 代码实现:
```python
# 定义 Student 类
class Student:
def __init__(self, id, name, score1, score2, score3):
self.id = id
self.name = name
self.score1 = score1
self.score2 = score2
self.score3 = score3
self.average = (score1 + score2 + score3) / 3
# 从键盘输入学生数据
students = []
for i in range(10):
id = input("请输入第{}个学生的学号:".format(i+1))
name = input("请输入第{}个学生的姓名:".format(i+1))
score1 = float(input("请输入第{}个学生的第1门课成绩:".format(i+1)))
score2 = float(input("请输入第{}个学生的第2门课成绩:".format(i+1)))
score3 = float(input("请输入第{}个学生的第3门课成绩:".format(i+1)))
students.append(Student(id, name, score1, score2, score3))
# 按平均成绩降序排序
students.sort(key=lambda x: x.average, reverse=True)
# 显示并写入文件
with open("result.txt", "w") as f:
f.write("学号\t姓名\t成绩1\t成绩2\t成绩3\t平均成绩\n")
for s in students:
f.write("{}\t{}\t{}\t{}\t{}\t{:.2f}\n".format(s.id, s.name, s.score1, s.score2, s.score3, s.average))
print("{}\t{}\t{}\t{}\t{}\t{:.2f}".format(s.id, s.name, s.score1, s.score2, s.score3, s.average))
```
运行代码后,会依次提示输入学生数据,然后按平均成绩降序显示并写入文件。注意,文件名为 result.txt,会在代码所在目录下生成。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)