用顺序表写一份包含学生学号,姓名班级,班号的学生表
时间: 2024-10-16 09:16:28 浏览: 26
定义一个包含学生信息(学号,姓名,成绩)的顺序表
在使用顺序表(也叫线性表)来表示包含学号、姓名、班级和班号的学生表时,你可以创建一个类来代表每个学生,并将它们存储在一个列表中。下面是一个简单的Python示例:
```python
class Student:
def __init__(self, id, name, class_name, class_number):
self.id = id
self.name = name
self.class_name = class_name
self.class_number = class_number
# 定义顺序学生列表
class SequentialStudentList:
def __init__(self, capacity=10):
self.students = [None] * capacity
self.size = 0
def add_student(self, student):
if self.size < len(self.students):
self.students[self.size] = student
self.size += 1
else:
self.resize(len(self.students) * 2) # 扩展列表
self.students[self.size] = student
self.size += 1
def resize(self, new_capacity):
new_students = [None] * new_capacity
for i in range(self.size):
new_students[i] = self.students[i]
self.students = new_students
def get_student_by_id(self, id):
for i in range(self.size):
if self.students[i].id == id:
return self.students[i]
return None
# 示例
student1 = Student(1001, '张三', '一班', 1)
student2 = Student(1002, '李四', '二班', 2)
student_list = SequentialStudentList()
student_list.add_student(student1)
student_list.add_student(student2)
# 查找特定学生的数据
target_id = 1001
found_student = student_list.get_student_by_id(target_id)
if found_student is not None:
print(f"{found_student.name}在班级{found_student.class_name}, 班号{found_student.class_number}")
else:
print(f"未找到学号为{target_id}的学生")
```
阅读全文