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

如何用字典实现Python的switch case?嵌套if代码优化求助

如何用字典或类似switch case的方式改写你的嵌套if代码

Python本身没有原生的switch-case语句,但用字典映射函数是替代这类多条件判断的绝佳方案,比嵌套if清爽太多,维护起来也更方便。先看看你的原代码:

message = event_data["event"]
if message.get("subtype") is None :
    if "friday" in message.get('text'):
        callfridayfunction()
    if "saturday" in message.get('text'):
        callsaturdayfunction()
    if "monday" in message.get('text'):
        callmondayfunction()

方案1:用字典映射实现(保留原多条件执行逻辑)

你的原代码是只要文本里包含对应关键词,就执行对应的函数(多个关键词匹配的话会执行多个函数),用字典可以这样改写:

message = event_data["event"]
if message.get("subtype") is None:
    # 先定义关键词和对应函数的映射关系
    keyword_to_func = {
        "friday": callfridayfunction,
        "saturday": callsaturdayfunction,
        "monday": callmondayfunction
    }
    text_content = message.get('text', '')  # 给个默认空字符串避免KeyError
    # 遍历字典,检查每个关键词是否在文本里,匹配就执行函数
    for keyword, func in keyword_to_func.items():
        if keyword in text_content:
            func()

这种写法的好处是:后续要加新的关键词(比如tuesday),直接在字典里加一行键值对就行,不用再新增if块,结构非常清晰。

方案2:用字典实现类似switch的单匹配逻辑

如果你想要类似switch-case的匹配第一个符合条件的就停止执行(也就是只会触发一个函数),可以给循环加个break:

message = event_data["event"]
if message.get("subtype") is None:
    keyword_to_func = {
        "friday": callfridayfunction,
        "saturday": callsaturdayfunction,
        "monday": callmondayfunction
    }
    text_content = message.get('text', '')
    for keyword, func in keyword_to_func.items():
        if keyword in text_content:
            func()
            break  # 找到第一个匹配的就退出循环,类似switch的break

方案3:Python 3.10+ 用原生match-case语法

如果你用的是Python 3.10及以上版本,还可以用官方新增的match-case语法,更接近传统的switch-case:

message = event_data["event"]
if message.get("subtype") is None:
    text_content = message.get('text', '')
    match text_content:
        case t if "friday" in t:
            callfridayfunction()
        case t if "saturday" in t:
            callsaturdayfunction()
        case t if "monday" in t:
            callmondayfunction()
        # 可选:处理没有匹配到的情况
        case _:
            print("No matching keyword found")

注意:这个写法和方案2逻辑一致,只会执行第一个匹配的分支,和原代码的多if逻辑不同,使用时要根据你的需求选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:37:12