如何在遍历字典列表的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
相关产品推荐
相关产品推荐

