我有一個代碼,我需要從學校名冊中洗掉一個人的條目。在代碼的最底部,我有 Stern 的引數,最后的列印陳述句列印了沒有 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')
uj5u.com熱心網友回復:
我的解決方案是使用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])
uj5u.com熱心網友回復:
在你的代碼的最后
course.dropstudent('Stren')
無法呼叫,因為在您的屬性定義中,您將“Student”物件作為引數傳遞,因此當您呼叫您的屬性時,您不能使用“字串”來呼叫它。
改用
Stud_Stren = Student('Brenda', 'Stern', 2.0)
course.dropstudent(Stud_Stren)
并使用Lukas Schmid為您的“drop_student”屬性提供的代碼并對其進行一些修改以使用您的學生物件的屬性(名字、姓氏、gpa),或者如果您不這樣做,則照原樣使用它不想傳遞學生物件并將您的電話替換為
course.dropstudent('Brenda', 'Stern')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/361573.html
上一篇:Tensorflow:ValueError:Input0isincompatiblewithlayermodel:expectedshape=(None,99),foundshape=(None,3)
