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

如何优雅处理if判断中的多个string.find()检查?

精简多条件判断的几种方案
  • 用in替代find简化基础判断
    原生字符串的in操作比find更直观,完全可以替代find != -1或find == -1的判断,先把最基础的条件简化:

    if a in string and b in string and c not in string and d not in string and string not in my_list:
    
  • 用all()批量处理同类条件
    如果后续需要增减需要检查的包含项或排除项,把它们归类到列表中,用all()统一判断,代码扩展性更强:

    required_items = [a, b]
    excluded_items = [c, d]
    if all(item in string for item in required_items) and all(item not in string for item in excluded_items) and string not in my_list:
    
  • 拆分为独立变量提升可读性
    把每个条件拆成命名清晰的布尔变量,即使条件复杂,也能一眼看懂逻辑:

    has_a = a in string
    has_b = b in string
    no_c = c not in string
    no_d = d not in string
    not_in_target_list = string not in my_list
    
    if has_a and has_b and no_c and no_d and not_in_target_list:
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:10:33