这是我作业的一部分,我之所以发布此内容是因为我对自己做错了什么感到困惑。
school = [['Abby Li'],
['Ella Wang', 'Danielle Han','Katherine Zhang', 'Morgan Liu'],
['Josh Li']
]
def searchStudent(school1, lastname1):
firstname = "Not"
lastname = "Found"
for grade in school1:
for student in grade:
name = student.split();
if name[1] == lastname1:
firstname = name[0]
lastname = name[1]
return firstname, lastname
while (True):
search = input("Please enter last name to search:")
if (search == "exit"):
break
foundFirst, foundLast = searchStudent(school, search)
print("found student: ", foundFirst, foundLast)
print("")
这是我的代码,但每当我输入“Li”作为姓氏时,只有 Josh 出现,而 Abby 没有出现。有人可以帮我解决吗?非常感谢!
另外,如果上面没有显示,这里是它的链接:code
最佳答案
缩进使 if
语句脱离 for 循环
此外,如果您想打印所有匹配项,则需要存储所有匹配项,因此您需要诸如列表之类的东西!
school = [['Abby Li'],
['Ella Wang', 'Danielle Han','Katherine Zhang', 'Morgan Liu'],
['Josh Li']
]
def searchStudent(school1, lastname1):
firstname = "Not"
lastname = "Found"
result = []
for grade in school1:
for student in grade:
name = student.split();
if name[1] == lastname1:
firstname = name[0]
lastname = name[1]
result.append([firstname, lastname])
return result
while (True):
search = input("Please enter last name to search:")
if (search == "exit"):
break
result = searchStudent(school, search)
for name in result: print("found student: ", name[0], name[1])
print("")
Please enter last name to search:Li
found student: Abby Li
found student: Josh Li
Please enter last name to search:exit
关于python - 修复不显示两个值的 python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63930609/