python之流程控制語句match-case詳解
更新時間:2025年03月18日 17:13:07 作者:Yant224
這篇文章主要介紹了python之流程控制語句match-case使用,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
match-case 語法詳解與實戰(zhàn)
match-case 是 Python 3.10+ 引入的模式匹配語法,可替代傳統(tǒng)的 if-elif-else 鏈,支持復雜數(shù)據(jù)解構和條件組合。
以下是 6 個核心使用場景與代碼案例:
一、基礎值匹配(類似 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ù)結構解構匹配
場景1:列表解構
def parse_command(cmd: list):
match cmd:
case ["start", *args]:
print(f"?? 啟動服務,參數(shù): {args}")
case ["stop", service_name]:
print(f"?? 停止服務: {service_name}")
case ["restart"]:
print("?? 重啟服務")
case _:
print("?? 無效指令")
parse_command(["start", "--port=8080"]) # ?? 啟動服務,參數(shù): ['--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("? 年齡不能為負數(shù)")
case _:
print("? 數(shù)據(jù)格式錯誤")
# 輸出:?? 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)) # ?? 立方體對角線四、帶守衛(wèi)條件的高級匹配
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"?? 偶數(shù): {n}")
case float(f) if f > 100.0:
print(f"?? 大額浮點數(shù): {f:.2f}")
case str(s) if len(s) > 50:
print("?? 長文本(已截斷):", s[:50] + "...")
case list([int(x), *rest]):
print(f"?? 整數(shù)列表,首元素: {x}, 長度: {len(rest)+1}")
case _:
print("? 未知數(shù)據(jù)類型")
handle_data(42) # ?? 偶數(shù): 42
handle_data([10, 20, 30]) # ?? 整數(shù)列表,首元素: 10, 長度: 3
六、協(xié)議解析實戰(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ù)包,載荷長度: {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ù)包...使用注意事項:
- 版本要求:僅支持 Python 3.10+
- 匹配順序:按代碼順序執(zhí)行,首個匹配成功即終止
- 通配符 _:必須放在最后,匹配所有未處理情況
- 性能優(yōu)化:復雜模式匹配可能影響性能,避免深層嵌套
與傳統(tǒng)寫法對比:
- 場景 match-case 寫法 if-elif 傳統(tǒng)寫法
- 多條件值匹配 使用 運算符簡潔組合 需要重復 or 連接條件
- 字典嵌套解構 直接提取多級字段 多層 get( ) 檢查和類型驗證
- 類屬性檢查 直接匹配對象屬性 需要 isinstance() 和屬性訪問
- 組合條件 case + if 守衛(wèi)條件 需要復雜布爾表達式
- 通過合理使用 match-case,可以使代碼更簡潔易讀,特別適用于:協(xié)議解析、API響應處理、復雜業(yè)務規(guī)則判斷等場景。建議搭配類型提示(Type Hints)使用效果更佳!
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Pandas中DataFrame.head()函數(shù)的具體使用
DataFrame.head()是Pandas庫中一個非常重要的函數(shù),用于返回DataFrame對象的前n行,本文主要介紹了Pandas中DataFrame.head()函數(shù)的具體使用,感興趣的可以了解一下2024-07-07
python讀取excel數(shù)據(jù)繪制簡單曲線圖的完整步驟記錄
這篇文章主要給大家介紹了關于python讀取excel數(shù)據(jù)繪制簡單曲線圖的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10

