简体   繁体   English

Python循环从列表中返回一个值

[英]Python loop to return one value from list

I'm having a bit of a problem understanding exactly how it works.我在理解它的工作原理时遇到了一些问题。 let's say that I have a list of students with their IDs, names and grades as following, and I would like to make a program that lets you input the student's ID and prints out the average grade:假设我有一个学生名单,他们的 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

this outputs this result这输出这个结果

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

How do I make it only print Carly?我如何让它只打印卡莉? thanks in advance!提前致谢!

Just remove the other prints, also a for loop and unpacking would make the code easier to read只需删除其他打印,也是一个 for 循环和解包将使代码更易于阅读

input_id = input("Enter Student id: ")
for student_id, student_name, student_grades in students:
    if input_id == student_id:
        print(student_name, sum(student_grades) / len(student_grades))
Enter Student id: 456
Carly 80.0

Your code needed some restructuring and some extra logic你的代码需要一些重组和一些额外的逻辑

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")
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM