我有一个代码,我需要从学校花名册中删除一个人的条目。在代码的最底部,我有一个参数Stern,最后的print语句打印没有Stern的花名册。我不知道如何从列表中删除人员,因为列表中有名字和姓氏,并且不允许将名字和姓氏都作为参数。我真的不知道在这种情况下是否可以使用.pop()或.remove()。我可以通过从列表中删除索引来删除名称吗?我也尝试过delattr
class Student:
def __init__(self, first, last, gpa):
self.first = first # first name
self.last = last # last name
self.gpa = gpa # grade point average
def get_gpa(self):
return self.gpa
def get_last(self):
return self.last
def to_string(self):
return self.first + ' ' + self.last + ' (GPA: ' + str(self.gpa) + ')'
class Course:
def __init__(self):
self.roster = [] # list of Student objects
**def drop_student(self, student):
#space where i remove one student**
def add_student(self, student):
self.roster.append(student)
def count_students(self):
return len(self.roster)
if __name__ == "__main__":
course = Course()
course.add_student(Student('Henry', 'Nguyen', 3.5))
course.add_student(Student('Brenda', 'Stern', 2.0))
course.add_student(Student('Lynda', 'Robinson', 3.2))
course.add_student(Student('Sonya', 'King', 3.9))
print('Course size:', course.count_students(),'students')
course.drop_student('Stern')
print('Course size after drop:', course.count_students(),'students')发布于 2021-11-20 20:04:26
我的解决方案是使用remove。但你必须首先抓取学生(例如,通过过滤/搜索列表)。
def drop_student(self, first, last):
matches = list(filter(lambda student: student.first == first and student.last == last, self.roster))
if len(matches) > 1:
raise Exception("Student not unique")
elif len(matches) < 1:
print(f"No student named {first} {last}")
else:
self.roster.remove(matches[0])发布于 2021-11-20 20:15:27
在代码的末尾
course.dropstudent('Stren')无法调用,因为在您的属性定义中,您将"Student“对象作为参数传递,因此当您调用您的属性时,不能使用”String“来调用它。
改为使用
Stud_Stren = Student('Brenda', 'Stern', 2.0)
course.dropstudent(Stud_Stren)并使用Lukas Schmid为您的"drop_student“属性提供的代码,并对其进行一些修改,以使用您的学生对象的属性(名字、姓氏、gpa),或者如果您不想传递学生对象并将调用替换为
course.dropstudent('Brenda', 'Stern')发布于 2021-11-24 17:16:38
您编写了course.drop_student('Stern'),但该名称不足以识别学生。因此,首先必须明确检索学生的关键字,例如(lastname,firstname)。然后,您可以编写类似以下内容:
def drop_student(self, last, first):
for i,student in enumerate(self.roster):
if student.last==last and student.first==first:
self.roster.pop(i)
...
course.drop_student('Stern','Brenda')https://stackoverflow.com/questions/70049361
复制相似问题