使用python写一个学生管理系统,增删改查和排序
时间: 2023-11-30 16:56:54 浏览: 86
好的,我可以帮你写一个基本的学生管理系统,包括增删改查和排序功能。以下是代码实现:
```python
class Student:
def __init__(self, name, age, gender, grade):
self.name = name
self.age = age
self.gender = gender
self.grade = grade
class StudentManager:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
def remove_student(self, name):
for student in self.students:
if student.name == name:
self.students.remove(student)
def update_student(self, name, age, gender, grade):
for student in self.students:
if student.name == name:
student.age = age
student.gender = gender
student.grade = grade
def search_student(self, name):
for student in self.students:
if student.name == name:
return student
return None
def sort_students(self, key):
if key == 'name':
self.students.sort(key=lambda x: x.name)
elif key == 'age':
self.students.sort(key=lambda x: x.age)
elif key == 'gender':
self.students.sort(key=lambda x: x.gender)
elif key == 'grade':
self.students.sort(key=lambda x: x.grade)
# 测试代码
if __name__ == '__main__':
manager = StudentManager()
# 添加学生
manager.add_student(Student('Tom', 18, 'Male', 90))
manager.add_student(Student('Lily', 17, 'Female', 85))
manager.add_student(Student('Lucy', 19, 'Female', 95))
# 查找学生
tom = manager.search_student('Tom')
print(tom.name, tom.age, tom.gender, tom.grade)
# 修改学生信息
manager.update_student('Tom', 19, 'Male', 92)
tom = manager.search_student('Tom')
print(tom.name, tom.age, tom.gender, tom.grade)
# 删除学生
manager.remove_student('Lily')
for student in manager.students:
print(student.name, student.age, student.gender, student.grade)
# 按照姓名排序
manager.sort_students('name')
for student in manager.students:
print(student.name, student.age, student.gender, student.grade)
```
这个学生管理系统使用了类和列表来存储学生信息,并提供了增删改查和排序功能。你可以根据自己的需求来修改代码。希望对你有所帮助。
阅读全文