You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在遍历字典列表的for循环中仅输出一次‘Book not found’提示

解决搜索字典列表时仅打印一次“Book not found”的问题

核心思路是先遍历列表查找目标书籍,用标记变量记录是否找到,遍历结束后再根据标记决定是否打印“未找到”提示,避免每次不匹配都输出重复信息。

修改后的代码如下:

found = False
for item in books_sorted:
    if item["title"] == search:
        print(item.get("title"), ",", item.get("author"))
        print("This book is in the collection")
        found = True
        # 找到目标后可提前跳出循环,提升效率(若需匹配多本可删除此行)
        break

if not found:
    print("Book not found")

代码说明:

  • 初始化found为False,用来标记是否找到目标书籍
  • 遍历过程中,一旦找到匹配项,打印书籍信息并将found设为True,用break终止循环(无需继续遍历剩余书籍)
  • 循环结束后,若found仍为False,说明遍历完所有书籍都未找到目标,此时仅打印一次“Book not found”

内容的提问来源于stack exchange,提问作者Wyatt C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 12:59:55