python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python流程控制语句match-case

python之流程控制语句match-case详解

作者:Yant224

这篇文章主要介绍了python之流程控制语句match-case使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

match-case 语法详解与实战

match-case 是 Python 3.10+ 引入的模式匹配语法,可替代传统的 if-elif-else 链,支持复杂数据解构和条件组合。

以下是 6 个核心使用场景与代码案例:

一、基础值匹配(类似 switch-case)

# 匹配 HTTP 状态码
status_code = 418

match status_code:
    case 200:
        print("✅ Success")
    case 301 | 302 | 307:
        print("↪️ Redirect")
    case 400 | 401 | 403:
        print("❌ Client Error")
    case 500:
        print("🔥 Server Error")
    case _:
        print(f"Unknown status: {status_code}")
        
输出:Unknown status: 418

二、数据结构解构匹配

场景1:列表解构

def parse_command(cmd: list):
    match cmd:
        case ["start", *args]:
            print(f"🚀 启动服务,参数: {args}")
        case ["stop", service_name]:
            print(f"🛑 停止服务: {service_name}")
        case ["restart"]:
            print("🔃 重启服务")
        case _:
            print("⚠️ 无效指令")

parse_command(["start", "--port=8080"])  # 🚀 启动服务,参数: ['--port=8080']
parse_command(["stop", "nginx"])         # 🛑 停止服务: nginx

场景2:字典解构

user_data = {
    "name": "John",
    "age": 25,
    "address": {"city": "New York", "zip": "10001"}
}

match user_data:
    case {"name": str(name), "age": int(age), "address": {"city": city}}:
        print(f"👤 {name} ({age}岁) 来自 {city}")
    case {"name": _, "age": int(age)} if age < 0:
        print("⛔ 年龄不能为负数")
    case _:
        print("❓ 数据格式错误")

# 输出:👤 John (25岁) 来自 New York

三、类实例模式匹配

class Vector:
    def __init__(self, x, y, z=0):
        self.x = x
        self.y = y
        self.z = z

def analyze_vector(vec):
    match vec:
        case Vector(0, 0, 0):
            print("⭕ 零向量")
        case Vector(x=0, y=0):
            print("📐 Z轴向量")
        case Vector(x, y, z) if x == y == z:
            print("🔶 立方体对角线")
        case Vector(_, _, z) if z != 0:
            print(f"🚀 三维向量 (Z={z})")
        case _:
            print("📏 普通二维向量")

analyze_vector(Vector(0, 0, 0))   # ⭕ 零向量
analyze_vector(Vector(2, 2, 2))   # 🔶 立方体对角线

四、带守卫条件的高级匹配

def process_transaction(tx):
    match tx:
        case {"type": "deposit", "amount": amt} if amt > 0:
            print(f"💰 存入 {amt} 元")
        case {"type": "withdraw", "amount": amt, "balance": bal} if amt <= bal:
            print(f"💸 取出 {amt} 元")
        case {"type": "withdraw", "amount": amt}:
            print(f"⛔ 余额不足,尝试取出 {amt} 元")
        case {"type": _}:
            print("❌ 无效交易类型")

process_transaction({"type": "withdraw", "amount": 500, "balance": 1000})
# 输出:💸 取出 500 元

五、类型验证与组合匹配

def handle_data(data):
    match data:
        case int(n) if n % 2 == 0:
            print(f"🔢 偶数: {n}")
        case float(f) if f > 100.0:
            print(f"📈 大额浮点数: {f:.2f}")
        case str(s) if len(s) > 50:
            print("📜 长文本(已截断):", s[:50] + "...")
        case list([int(x), *rest]):
            print(f"📦 整数列表,首元素: {x}, 长度: {len(rest)+1}")
        case _:
            print("❓ 未知数据类型")

handle_data(42)            # 🔢 偶数: 42
handle_data([10, 20, 30])  # 📦 整数列表,首元素: 10, 长度: 3

六、协议解析实战案例

def parse_packet(packet: bytes):
    match packet:
        case b'\x08\x00' | b'\x08\x01':
            print("📡 ICMP 数据包")
        case b'\x45' + payload:
            print(f"🌐 IPv4 数据包,载荷长度: {len(payload)}")
        case [version, _, *rest] if version >> 4 == 6:
            print("🌐 IPv6 数据包")
        case _:
            print("❌ 未知协议")

parse_packet(b'\x45\x00\x00\x1c\x00\x01\x00\x00\x40')  # 🌐 IPv4 数据包...

使用注意事项:

与传统写法对比:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文