学生管理系统python线性表插入删除
时间: 2023-10-15 22:04:25 浏览: 47
以下是一个简单的学生管理系统Python代码,其中包括线性表的插入和删除操作:
```python
class Student:
def __init__(self, name, id):
self.name = name
self.id = id
class StudentList:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
def remove_student(self, id):
for student in self.students:
if student.id == id:
self.students.remove(student)
return True
return False
def display_students(self):
for student in self.students:
print("Name: {} \t ID: {}".format(student.name, student.id))
# Sample Usage
student_list = StudentList()
student_list.add_student(Student("Alice", "001"))
student_list.add_student(Student("Bob", "002"))
student_list.add_student(Student("Charlie", "003"))
student_list.display_students()
# Remove a student
if student_list.remove_student("002"):
print("Student removed successfully.")
else:
print("Student not found.")
student_list.display_students()
```
在上面的代码中,`Student`类表示一个学生对象,包含学生的姓名和学号。`StudentList`类表示学生列表,其中包含一个学生对象列表。`add_student`方法用于将一个学生对象添加到列表中,`remove_student`方法用于根据学号从列表中删除一个学生对象,`display_students`方法用于显示列表中所有学生的信息。
在上面的代码中,我们可以看到如何使用Python列表来实现线性表的功能。`add_student`方法使用`append`方法将学生对象添加到列表末尾,`remove_student`方法使用`remove`方法根据学号从列表中删除一个学生对象。这些列表方法实际上是Python内置的线性表方法,我们可以使用它们来方便地管理学生列表。