【发布时间】:2019-05-16 16:10:27
【问题描述】:
伙计们!我有一个具有 3 个属性('name'、'id'、'gpa')的类('Student')。然后我有一个该类对象的列表(“学生”)。我需要根据属性列表“名称”的第一个字母(“键”)将“学生”的所有实例保存到另一个列表中。因此,对于以“key”开头的每个“name”,新列表应该包含“students.name”、“students.id”、“students.gpa”。
我试过studentsNames = filter(lambda x: x.startswith(key), students) 但列表('studentsNames')出现空,即使有以'key'开头的名字。
这是代码示例。全班学生在这里:https://github.com/lelecarabina/python3/blob/master/Student.py,下面的完整代码在这里:https://github.com/lelecarabina/python3/blob/master/StudentFinder.py
...
#Create new Student object students
students = [Student((),(),())] * numStudents
print("All Students:")
# Initialize List of Student 'students' with **CONSTRUCTOR** and Print
for x in range(numStudents):
students[x] = (Student(names[x], (1101 + x), (gpas[rand]))) # constructor
print(students[x].getName(), students[x].getId(), students[x].getGpa())
#prompt user for input
key = input("\nEnter the first letter of student's name: ")
for x in range(len(students)):
studentsNames = [item for item in students if students[x].name[0] == key]
#print(studentsNames)
#print sorted list header
print("Students names starting with '{}'".format(key.upper()))
#loop through sorted list
for x in range(numStudents):
#end loop if no student's names matches user's input
if studentsNames == "":
print("NOT FOUND")
break
# end if statement
#print sorted list is student's name matches user's input, along with name's id and gpa
for name in studentsNames:
if name == students[x].name:
print(" Name: {} -> ID: {} -> GPA: {}".format(students[x].name, students[x].id, students[x].gpa))
# end if statement
# end for each loop
# end for loop
#message to user, ending program
print("Program Ended.")
它应该打印: 名称:... -> ID:... -> GPA: ... 其中点是从“学生”中提取的信息。 但它打印: “以‘L’开头的学生名字 程序已结束。”
请帮忙。
【问题讨论】:
标签: list oop search python-3.7