Python 教程 / 模式匹配

模式匹配

学习Python 3.10引入的match-case语句,实现更优雅的模式匹配。

版本要求

模式匹配(match-case)需要Python 3.10或更高版本。如果你的Python版本较低,请先升级。

基本match-case

match-case类似于其他语言的switch语句,但更加强大。

Python
def get_day_type(day):
    match day:
        case "Saturday" | "Sunday":  # 或运算
            return "周末"
        case "Monday" | "Tuesday" | "Wednesday":
            return "工作日"
        case _:
            return "未知"

print(get_day_type("Saturday"))  # 周末
print(get_day_type("Monday"))    # 工作日 

序列模式

可以匹配列表、元组等序列类型。

Python
def parse_point(point):
    match point:
        case (0, 0):
            return "原点"
        case (x, 0):
            return f"X轴上的点: {x}"
        case (0, y):
            return f"Y轴上的点: {y}"
        case (x, y):
            return f"普通点: ({x}, {y})"
        case _:
            return "无效坐标"

print(parse_point((0, 0)))   # 原点
print(parse_point((5, 0)))   # X轴上的点: 5
print(parse_point((3, 4)))   # 普通点: (3, 4) 

字典模式

可以匹配字典结构。

Python
def parse_command(cmd):
    match cmd:
        case {"action": "start"}:
            return "开始执行"
        case {"action": "stop"}:
            return "停止执行"
        case {"action": action, "timeout": t}:
            return f"执行{action},超时{t}秒"
        case _:
            return "未知命令"

print(parse_command({"action": "start"}))
print(parse_command({"action": "start", "timeout": 30})) 

类模式

可以匹配类实例的属性。

Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def get_location(point):
    match point:
        case Point(x=0, y=0):
            return "原点"
        case Point(x=x, y=0):
            return f"X轴: {x}"
        case Point() as p:
            return f"普通点({p.x}, {p.y})" 

守卫子句

使用if添加额外的条件判断。

Python
def classify_number(n):
    match n:
        case x if x > 0:
            return "正数"
        case x if x < 0:
            return "负数"
        case _:
            return "零"

print(classify_number(10))   # 正数
print(classify_number(-5))   # 负数
print(classify_number(0))    # 零 
🐍 Python 在线代码编辑器
📝 运行结果