首页 > 解决方案 > python else部分if运行多次,如何解决

问题描述

这是我的代码,用于显示搜索记录并在没有发现时显示通知 usr。问题:else 部分运行的次数与外循环一样多。

entries = [{'First Name': 'Sher', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '2989484'},
           {'First Name': 'Ali', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '398439'},
           {'First Name': 'Talha', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '3343434'}]    
search = input("type your search: ")
            print(search)
            for person in entries:
                # print(person)
                if person["Last Name"] == search:
                    print("Here are the records found for your search")
                    for e in person:
                        print(e, ":", person[e])
                else:
                    print("There is no record found as you search Keyword")

标签: pythonlistdictionaryif-statement

解决方案


那是因为每次迭代你只检查 1 个人,如果你没有找到你要找的东西,你正在打印它不存在。
这实际上是一种不良行为。

更好的解决方案是简单地查看您需要的一组值:

...
search = input("type your search: ")
founds = [entry for entry in entries if entry["Last Name"] == search)]  ## filtering only records that match what we need using list comprehension
if founds:
    for found in founds:
        * print info  *
else:
    print("There is no record found as you search Keyword")

推荐阅读