Python循环遍历列表时重复输出‘Not Found’问题排查与解决
问题:修复联系人查询代码的多余"Not Found"输出
我想要实现:输入的名字在contacts列表里时返回对应信息,不存在则返回“Not Found”。现有Python代码如下:
contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] name = input() for x in contacts: if name == x[0]: print("%s is %d" % (x[0], x[1])) break else: print("Not Found")
当输入Amanda时,输出结果为:
Not Found Not Found Not Found Amanda is 63
请问如何消除这三条“Not Found”,原因是什么?
问题原因
你的代码里,else是和循环内的if绑定的每一次循环:只要当前遍历的联系人名字不匹配,就会立刻打印"Not Found"。输入Amanda时,前三个联系人(James、Amy、John)都不匹配,所以每次循环都会触发else块打印一次,直到找到Amanda才break停止循环。
修复方案
这里提供三种实用的修复方式:
方式1:用标志变量跟踪是否找到
先初始化一个标志位,循环结束后根据标志判断是否打印"Not Found":
contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] name = input() found = False for x in contacts: if name == x[0]: print("%s is %d" % (x[0], x[1])) found = True break if not found: print("Not Found")
方式2:转换为字典(更高效)
把列表转成字典后,直接通过键查找,代码更简洁,查询效率也更高(O(1)时间复杂度):
contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] # 转换为字典,名字作为键,年龄作为值 contact_dict = dict(contacts) name = input() if name in contact_dict: print(f"{name} is {contact_dict[name]}") else: print("Not Found")
方式3:利用Python的for-else特性
Python的for循环可以搭配else块,只有当循环正常结束(没有触发break)时,才会执行else里的代码:
contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] name = input() for x in contacts: if name == x[0]: print("%s is %d" % (x[0], x[1])) break else: # 只有循环没找到匹配项、正常结束时才会执行这里 print("Not Found")
内容的提问来源于stack exchange,提问作者Shotgun
相关产品推荐
相关产品推荐

