Python中的match-case语句:模式匹配

Python 3.10引入了令人期待的模式匹配功能——match-case语句,这为Python开发者提供了更强大的条件判断工具。与传统if-elif-else链相比,match-case让代码更加清晰易读。

基本用法

match-case的基本语法类似于其他语言中的switch语句,但功能更强大:

def handle_http_status(status):
    match status:
        case 200:
            return "成功"
        case 404:
            return "未找到"
        case 500:
            return "服务器错误"
        case _:
            return "未知状态码"
 
 

高级模式匹配

match-case的真正威力在于其模式匹配能力:

def process_data(data):
    match data:
        case []:
            print("空列表")
        case [x]:
            print(f"单元素列表: {x}")
        case [x, y, *rest]:
            print(f"多元素列表: {x}, {y}, 其余: {rest}")
        case _:
            print("其他数据类型")
 
 

类型检查

还可以结合类型提示进行模式匹配:

def type_check(value):
    match value:
        case int() | float():
            print("数字类型")
        case str():
            print("字符串类型")
        case list() | tuple():
            print("集合类型")
        case _:
            print("未知类型")
 
 

match-case语句让Python代码更加表达性强,特别是在处理复杂数据结构时,能够显著提高代码的可读性和可维护性。

posted @ 2025-10-27 11:43  u95900090  阅读(37)  评论(0)    收藏  举报