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

检查字符串列表是否在字符串中:两段代码的执行差异与报错分析

两段代码执行差异的原因分析

可正常执行的代码

excluded_strings = ['excluded', 'decrypted', 'extracted_pdf_text.txt']

def excl_file_with_str(rec_file_name):
   
    string_match = [True for excluded_string in excluded_strings if excluded_string in rec_file_name]

    if True in string_match:
        return None
    else:
        return rec_file_name

触发错误的代码

excluded_strings = ['excluded', 'decrypted', 'extracted_pdf_text.txt']

def excl_file_with_str(rec_file_name):

    for excluded_string in excluded_strings:
        if excluded_string in rec_file_name:
            string_match = True

    if True in string_match:
        return None
    else:
        return rec_file_name

差异及报错原因

第一段代码的执行逻辑

string_match是通过列表推导式定义的——无论传入的文件名是否匹配到排除字符串,列表推导式都会生成一个列表(匹配到就生成包含True的列表,没匹配到就生成空列表[])。也就是说,string_match变量一定会被初始化,后续判断True in string_match时能正常找到变量。

第二段代码的报错根源

string_match只在for循环内部的if分支成立时才会被赋值。如果传入的rec_file_name不包含任何excluded_strings里的内容,整个for循环里的if分支根本不会执行,string_match就从来没被定义过。当后续代码尝试访问这个未定义的变量时,Python就会抛出UnboundLocalError: local variable 'string_match' referenced before assignment错误。

第二段代码的修复示例

可以提前给变量初始化默认值,避免未定义的情况:

excluded_strings = ['excluded', 'decrypted', 'extracted_pdf_text.txt']

def excl_file_with_str(rec_file_name):
    is_excluded = False
    for excluded_string in excluded_strings:
        if excluded_string in rec_file_name:
            is_excluded = True
            break  # 找到匹配后提前退出循环,提升效率

    return None if is_excluded else rec_file_name

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:01:17