如何基于Student类数据从列表中移除留校察看的学生
解决方案
你原代码存在一个关键问题:把Student实例的创建逻辑写在了类的__init__方法内部,这会导致每次初始化Student对象时都重复创建这些实例,而且单独的Students名字列表无法关联到对应学生的onProbation状态,没法直接过滤。
要实现需求,需要先把学生实例和名字的关联关系建立起来,再进行过滤,以下是两种可行的实现方式:
方式一:通过实例列表筛选
直接存储所有学生实例,遍历筛选出符合条件的名字:
class Student: def __init__(self, name, major, gpa, onProbation): self.name = name self.major = major self.gpa = gpa self.onProbation = onProbation # 将实例创建移到类外部,避免重复初始化 student1 = Student("Josh", "Business", 3.8, False) student2 = Student("Maya", "Accountancy", 2.5, True) student3 = Student("Dan", "Psychology", 1.2, True) student4 = Student("Keon", "Biomedical Engineering", 4.0, False) student5 = Student("Michelle", "Medicine", 3.7, False) student6 = Student("Joey", "Law", 4.0, False) # 存储所有学生实例 all_students = [student1, student2, student3, student4, student5, student6] # 筛选出未留校察看的学生名字 Students = [stu.name for stu in all_students if not stu.onProbation] print(Students) # 输出: ['Josh', 'Keon', 'Michelle', 'Joey']
方式二:通过字典映射关联名字与实例
如果需要保留原有的Students名字列表结构,可以用字典建立名字到实例的映射:
class Student: def __init__(self, name, major, gpa, onProbation): self.name = name self.major = major self.gpa = gpa self.onProbation = onProbation # 用字典存储名字到对应实例的映射 student_map = { "Josh": Student("Josh", "Business", 3.8, False), "Maya": Student("Maya", "Accountancy", 2.5, True), "Dan": Student("Dan", "Psychology", 1.2, True), "Keon": Student("Keon", "Biomedical Engineering", 4.0, False), "Michelle": Student("Michelle", "Medicine", 3.7, False), "Joey": Student("Joey", "Law", 4.0, False) } # 原名字列表 Students = ["Josh", "Maya", "Dan", "Keon", "Michelle", "Joey"] # 过滤掉处于留校察看状态的学生 Students = [name for name in Students if not student_map[name].onProbation] print(Students) # 输出: ['Josh', 'Keon', 'Michelle', 'Joey']
核心逻辑都是先让学生的名字和对应的onProbation状态绑定,再通过列表推导式筛选出符合要求的名字。
内容的提问来源于stack exchange,提问作者ske
相关产品推荐
相关产品推荐

