[英]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
我如何讓它只打印卡莉? 提前致謝!
只需刪除其他打印,也是一個 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
你的代碼需要一些重組和一些額外的邏輯
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.