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