python - 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")
解决方案
那是因为每次迭代你只检查 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")
推荐阅读
- spring - 使用 ReactiveCrudRepository 的多租户
- reactjs - 为什么 react 组件返回多个元素?
- php - 在 Laravel 的 iframe 的 src 中,HTTP 被更改为 HTTPS
- cmake - CMAKE_PREFIX_PATH 和 CMAKE_MODULE_PATH 都是空的,find_package 仍然有效
- javascript - 为什么我的 onscroll 功能在元素完全滚动之前停止?
- javascript - 将鼠标悬停在特定框上时如何查看详细信息?
- git - (如何)Github 仓库的所有者可以访问合作者的 IP 地址吗?
- sql - ORACLE SQL:如何获取特定单词之前的文本
- java - 我们使用 java 8 和 Tomcat 版本 7.0.84,我们得到 400 无效字符错误
- java - 在 Hibernate/JPA 中,我应该在哪里以及在哪个用例中使用 SessionFactory 和 Session