python之流程控制語(yǔ)句match-case詳解
match-case 語(yǔ)法詳解與實(shí)戰(zhàn)
match-case 是 Python 3.10+ 引入的模式匹配語(yǔ)法,可替代傳統(tǒng)的 if-elif-else 鏈,支持復(fù)雜數(shù)據(jù)解構(gòu)和條件組合。
以下是 6 個(gè)核心使用場(chǎng)景與代碼案例:
一、基礎(chǔ)值匹配(類(lèi)似 switch-case)
# 匹配 HTTP 狀態(tài)碼
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二、數(shù)據(jù)結(jié)構(gòu)解構(gòu)匹配
場(chǎng)景1:列表解構(gòu)
def parse_command(cmd: list):
match cmd:
case ["start", *args]:
print(f"?? 啟動(dòng)服務(wù),參數(shù): {args}")
case ["stop", service_name]:
print(f"?? 停止服務(wù): {service_name}")
case ["restart"]:
print("?? 重啟服務(wù)")
case _:
print("?? 無(wú)效指令")
parse_command(["start", "--port=8080"]) # ?? 啟動(dòng)服務(wù),參數(shù): ['--port=8080']
parse_command(["stop", "nginx"]) # ?? 停止服務(wù): nginx場(chǎng)景2:字典解構(gòu)
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}歲) 來(lái)自 {city}")
case {"name": _, "age": int(age)} if age < 0:
print("? 年齡不能為負(fù)數(shù)")
case _:
print("? 數(shù)據(jù)格式錯(cuò)誤")
# 輸出:?? John (25歲) 來(lái)自 New York
三、類(lèi)實(shí)例模式匹配
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("?? 立方體對(duì)角線")
case Vector(_, _, z) if z != 0:
print(f"?? 三維向量 (Z={z})")
case _:
print("?? 普通二維向量")
analyze_vector(Vector(0, 0, 0)) # ? 零向量
analyze_vector(Vector(2, 2, 2)) # ?? 立方體對(duì)角線四、帶守衛(wèi)條件的高級(jí)匹配
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("? 無(wú)效交易類(lèi)型")
process_transaction({"type": "withdraw", "amount": 500, "balance": 1000})
# 輸出:?? 取出 500 元五、類(lèi)型驗(yàn)證與組合匹配
def handle_data(data):
match data:
case int(n) if n % 2 == 0:
print(f"?? 偶數(shù): {n}")
case float(f) if f > 100.0:
print(f"?? 大額浮點(diǎn)數(shù): {f:.2f}")
case str(s) if len(s) > 50:
print("?? 長(zhǎng)文本(已截?cái)啵?", s[:50] + "...")
case list([int(x), *rest]):
print(f"?? 整數(shù)列表,首元素: {x}, 長(zhǎng)度: {len(rest)+1}")
case _:
print("? 未知數(shù)據(jù)類(lèi)型")
handle_data(42) # ?? 偶數(shù): 42
handle_data([10, 20, 30]) # ?? 整數(shù)列表,首元素: 10, 長(zhǎng)度: 3
六、協(xié)議解析實(shí)戰(zhàn)案例
def parse_packet(packet: bytes):
match packet:
case b'\x08\x00' | b'\x08\x01':
print("?? ICMP 數(shù)據(jù)包")
case b'\x45' + payload:
print(f"?? IPv4 數(shù)據(jù)包,載荷長(zhǎng)度: {len(payload)}")
case [version, _, *rest] if version >> 4 == 6:
print("?? IPv6 數(shù)據(jù)包")
case _:
print("? 未知協(xié)議")
parse_packet(b'\x45\x00\x00\x1c\x00\x01\x00\x00\x40') # ?? IPv4 數(shù)據(jù)包...使用注意事項(xiàng):
- 版本要求:僅支持 Python 3.10+
- 匹配順序:按代碼順序執(zhí)行,首個(gè)匹配成功即終止
- 通配符 _:必須放在最后,匹配所有未處理情況
- 性能優(yōu)化:復(fù)雜模式匹配可能影響性能,避免深層嵌套
與傳統(tǒng)寫(xiě)法對(duì)比:
- 場(chǎng)景 match-case 寫(xiě)法 if-elif 傳統(tǒng)寫(xiě)法
- 多條件值匹配 使用 運(yùn)算符簡(jiǎn)潔組合 需要重復(fù) or 連接條件
- 字典嵌套解構(gòu) 直接提取多級(jí)字段 多層 get( ) 檢查和類(lèi)型驗(yàn)證
- 類(lèi)屬性檢查 直接匹配對(duì)象屬性 需要 isinstance() 和屬性訪問(wèn)
- 組合條件 case + if 守衛(wèi)條件 需要復(fù)雜布爾表達(dá)式
- 通過(guò)合理使用 match-case,可以使代碼更簡(jiǎn)潔易讀,特別適用于:協(xié)議解析、API響應(yīng)處理、復(fù)雜業(yè)務(wù)規(guī)則判斷等場(chǎng)景。建議搭配類(lèi)型提示(Type Hints)使用效果更佳!
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
matlab中實(shí)現(xiàn)矩陣刪除一行或一列的方法
下面小編就為大家分享一篇matlab中實(shí)現(xiàn)矩陣刪除一行或一列的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
Python的元組和字典知識(shí)點(diǎn)超詳細(xì)講解
這篇文章主要介紹了Python中元組和字典兩種數(shù)據(jù)結(jié)構(gòu)的基本用法,包括初始化、索引、拼接、剔除、重復(fù)、最大值和最小值、鍵值查詢(xún)、獲取對(duì)應(yīng)值、剔除、更新、添加和計(jì)算數(shù)量等操作,需要的朋友可以參考下2025-01-01
Python中實(shí)現(xiàn)循環(huán)遍歷的完全指南
循環(huán)是編程中最核心的概念之一,它允許我們重復(fù)執(zhí)行代碼塊,Python提供了兩種主要的循環(huán)結(jié)構(gòu),即for循環(huán)和while循環(huán),下面小編就和大家詳細(xì)介紹一下吧2026-02-02
python下10個(gè)簡(jiǎn)單實(shí)例代碼
最近學(xué)python比較順手,找到感覺(jué)了,所以,我想把我用來(lái)練習(xí)的實(shí)例題目分享出來(lái),有興趣的朋友可以關(guān)注一下。 文章分為10篇,每篇10題,共100道實(shí)例。后續(xù)如果需要可以增加2017-11-11
python筆記之mean()函數(shù)實(shí)現(xiàn)求取均值的功能代碼
這篇文章主要介紹了python筆記之mean()函數(shù)實(shí)現(xiàn)求取均值的功能代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
Python爬蟲(chóng)回測(cè)股票的實(shí)例講解
在本篇文章里小編給大家整理的是一篇關(guān)于Python爬蟲(chóng)回測(cè)股票的實(shí)例講解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-01-01
Python使用psutil庫(kù)對(duì)系統(tǒng)數(shù)據(jù)進(jìn)行采集監(jiān)控的方法
利用psutil庫(kù)可以獲取系統(tǒng)的一些信息,如cpu,內(nèi)存等使用率,從而可以查看當(dāng)前系統(tǒng)的使用情況,實(shí)時(shí)采集這些信息可以達(dá)到實(shí)時(shí)監(jiān)控系統(tǒng)的目的。本文給大家介紹Python psutil系統(tǒng)監(jiān)控的相關(guān)知識(shí),感興趣的朋友一起看看吧2021-08-08

