Python 循环到 return 列表中的一个值

Python loop to return one value from list

我在理解其工作原理时遇到了一些问题。比方说,我有一个学生名单,他们的 ID、姓名和成绩如下,我想制作一个程序,让您输入学生的 ID 并打印出平均成绩:

students = [ #list of id, name and grades
    ("123", "Adam", [58, 68, 74]), \
    ("925", "Bob", []), \
    ("456", "Carly", [68, 72, 100]), \
    ("888", "Deborah", [68, 99, 100]), \
    ("789", "Ethan", [52, 88, 73])
]
input_id = str(input("Enter Student id: "))
student_num = 0
while student_num < len(students):
  student = students[student_num]
  student_id = student[0]
  student_name = student[1]
  student_grades = student[2]
  if input_id == student_id:
    print(student_name, sum(student_grades)/len(student_grades))
  elif student_grades == []:
    print(student_name, "has no grades")
  else: print(input_id, "not found")
  student_num += 1

这输出这个结果

> Enter Student id: 456
> 456 not found
> Bob has no grades
> Carly 80.0
> 456 not found
> 456 not found

如何让它只打印 Carly? 提前致谢!

使用for循环,解包后代码更易读,那么在if input_id == student_id之后要将找到的人相关的2个打印件放在if input_id == student_id之后,可以使用for/else结构很好,如果你没有找到你没有使用 break 指令(停止循环)的人,那么你进入最后的 else

input_id = input("Enter Student id: ")
for student_id, student_name, student_grades in students:
    if input_id == student_id:
        if not student_grades:
            print(student_name, "has no grades")
        else:
            print(student_name, sum(student_grades) / len(student_grades))
        break
else:
    print(input_id, "not found")
Enter Student id: 456
Carly 80.0

您的代码需要一些重构和一些额外的逻辑

students = [ #list of id, name and grades
    ("123", "Adam", [58, 68, 74]), \
    ("925", "Bob", []), \
    ("456", "Carly", [68, 72, 100]), \
    ("888", "Deborah", [68, 99, 100]), \
    ("789", "Ethan", [52, 88, 73])
]
input_id = str(input("Enter Student id: "))
student_num = 0
found = False
while student_num < len(students):
    student = students[student_num]
    student_id = student[0]
    if input_id == student_id:
        found = True
        student_name = student[1]
        student_grades = student[2]
        if student_grades == []:
            print(student_name, "has no grades")
            
        else:
            print(student_name, sum(student_grades)/len(student_grades))
            
    
    student_num += 1
if found == False:
    print(input_id, "not found")