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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:40:01