编写一个程序,实现一下功能,要求 设计一个学生student类,包含学号、姓名、出生日期、性别等字段 从input.txt(从附件下载)中读取其中的学生信息,并存入学生集合list中 对学生集合list进行排序,按照出生日期从早到晚排序(即年龄由大到小) 将排序后的学生集合list输出到output.txt文件中,输出格式同input.txt:一行一个学生,依次输出学号、姓名、出生日期、性别并用空格隔开
时间: 2024-02-25 14:58:08 浏览: 20
好的,我理解了你的要求。以下是实现该功能的 Python 代码:
```python
from datetime import datetime
# 定义学生类
class Student:
def __init__(self, id, name, birth, gender):
self.id = id
self.name = name
self.birth = datetime.strptime(birth, '%Y-%m-%d')
self.gender = gender
def __str__(self):
return f'{self.id} {self.name} {self.birth.strftime("%Y-%m-%d")} {self.gender}'
# 读取学生信息
students = []
with open('input.txt', 'r') as f:
for line in f:
id, name, birth, gender = line.strip().split()
students.append(Student(id, name, birth, gender))
# 按出生日期排序
students.sort(key=lambda s: s.birth)
# 将排序后的学生信息输出到文件
with open('output.txt', 'w') as f:
for s in students:
f.write(str(s) + '\n')
```
你可以将上述代码保存为 `sort_students.py` 文件,并将 `input.txt` 文件放在同一目录下,然后在命令行中执行 `python sort_students.py` 命令,即可生成排序后的学生信息文件 `output.txt`。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)