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

Python 3.10中match...case匹配后执行代码的简洁实现方式

优雅实现match...case匹配后的通用代码执行

这里有几种更简洁的方案解决你的问题:

方案一:封装通用逻辑为独立函数

把需要执行的通用代码抽成单独函数,在每个匹配的case中调用,既避免重复代码,又保持逻辑清晰:

def common_post_action():
    print("Something happened")

def foo(x):
    match x:
        case "Hello,":
            a()
            common_post_action()
        case "World!":
            b()
            common_post_action()
        case "foobar":
            c()
            common_post_action()
        case _:
            print("Something didn't happen :(")

方案二:用返回值标记匹配状态

把match逻辑封装成内部函数,通过返回值判断是否匹配成功,主流程会更简洁直观:

def foo(x):
    def process_match():
        match x:
            case "Hello,":
                a()
                return True
            case "World!":
                b()
                return True
            case "foobar":
                c()
                return True
            case _:
                return False
    
    print("Something happened" if process_match() else "Something didn't happen :(")

方案三:简化标记变量写法

如果不想额外封装函数,也可以把原来的标记变量改成布尔类型,让代码更紧凑:

def foo(x):
    matched = False
    match x:
        case "Hello,":
            a()
            matched = True
        case "World!":
            b()
            matched = True
        case "foobar":
            c()
            matched = True
    
    print("Something happened" if matched else "Something didn't happen :(")

这几种方案都能避免冗余代码,同时比你原来的写法更简洁优雅。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:42:33