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

Pythonic写法:简化多值匹配的if条件判断

简化该Python条件判断的几种方法
  • 使用成员运算符in
    把目标字符串存入集合(查找效率优于列表),只需调用一次lower(),代码更简洁:

    if user_input.lower() in {'yes', 'y'}:
        print('Done!')
    
  • 提前缓存转换后的结果
    如果后续还要用到小写形式的输入,先将其赋值给变量,避免重复调用lower():

    lower_input = user_input.lower()
    if lower_input == 'yes' or lower_input == 'y':
        print('Done!')
    
  • 前缀匹配(按需使用)
    若业务允许匹配以yes或y开头的输入(比如yes please),可以用startswith:

    if user_input.lower().startswith(('yes', 'y')):
        print('Done!')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:10:30