Python循环中if语句重复输出问题:需仅打印一次‘no injury’
解决Python代码重复打印问题
原代码如下:
token_list = ['lg', 'was', 'beaten'] defined_words = ['hand', 'leg', 'head', 'arm', 'finger', 'wrist', 'thigh'] for i in range(0, len(token_list), 1): if token_list[i] in defined_words: print(token_list[i]) break elif token_list not in defined_words: print('no injury')
问题原因
原代码把打印逻辑放在循环内部,每遍历一个不匹配的元素就会执行一次print('no injury'),导致重复输出三次。另外token_list not in defined_words的判断逻辑有误,应该针对单个token而非整个列表,但核心问题是循环内重复触发打印操作。
解决方案
方案一:使用标记变量
通过布尔变量记录是否找到匹配项,循环结束后统一判断是否打印提示:
token_list = ['lg', 'was', 'beaten'] defined_words = ['hand', 'leg', 'head', 'arm', 'finger', 'wrist', 'thigh'] found_match = False for token in token_list: if token in defined_words: print(token) found_match = True break if not found_match: print('no injury')
方案二:用生成器表达式简化逻辑
利用next()直接获取第一个匹配的token,未找到则返回None,再根据结果输出:
token_list = ['lg', 'was', 'beaten'] defined_words = ['hand', 'leg', 'head', 'arm', 'finger', 'wrist', 'thigh'] first_match = next((t for t in token_list if t in defined_words), None) if first_match: print(first_match) else: print('no injury')
内容的提问来源于stack exchange,提问作者Oghenetejiri Obesare
相关产品推荐
相关产品推荐

