欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python之流程控制語句match-case詳解

 更新時(shí)間:2025年03月18日 17:13:07   作者:Yant224  
這篇文章主要介紹了python之流程控制語句match-case使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

match-case 語法詳解與實(shí)戰(zhàn)

match-case 是 Python 3.10+ 引入的模式匹配語法,可替代傳統(tǒng)的 if-elif-else 鏈,支持復(fù)雜數(shù)據(jù)解構(gòu)和條件組合。

以下是 6 個(gè)核心使用場(chǎng)景與代碼案例:

一、基礎(chǔ)值匹配(類似 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("?? 無效指令")

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}歲) 來自 {city}")
    case {"name": _, "age": int(age)} if age < 0:
        print("? 年齡不能為負(fù)數(shù)")
    case _:
        print("? 數(shù)據(jù)格式錯(cuò)誤")

# 輸出:?? John (25歲) 來自 New York

三、類實(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("? 無效交易類型")

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

五、類型驗(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ù)類型")

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)寫法對(duì)比:

  • 場(chǎng)景 match-case 寫法 if-elif 傳統(tǒng)寫法
  • 多條件值匹配 使用 運(yùn)算符簡(jiǎn)潔組合 需要重復(fù) or 連接條件
  • 字典嵌套解構(gòu) 直接提取多級(jí)字段 多層 get( ) 檢查和類型驗(yàn)證
  • 類屬性檢查 直接匹配對(duì)象屬性 需要 isinstance() 和屬性訪問
  • 組合條件 case + if 守衛(wèi)條件 需要復(fù)雜布爾表達(dá)式
  • 通過合理使用 match-case,可以使代碼更簡(jiǎn)潔易讀,特別適用于:協(xié)議解析、API響應(yīng)處理、復(fù)雜業(yè)務(wù)規(guī)則判斷等場(chǎng)景。建議搭配類型提示(Type Hints)使用效果更佳!

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python常見數(shù)據(jù)類型處理詳細(xì)代碼示例

    Python常見數(shù)據(jù)類型處理詳細(xì)代碼示例

    這篇文章主要介紹了Python常見數(shù)據(jù)類型處理的相關(guān)資料,包括Number、String、bool、List、Tuple、Set和Dictionary,每種數(shù)據(jù)類型都有其特定的用途和操作方法,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2025-04-04
  • Python如何用pip命令升級(jí)所有可以升級(jí)的(過時(shí)的)包

    Python如何用pip命令升級(jí)所有可以升級(jí)的(過時(shí)的)包

    這篇文章主要介紹了Python如何用pip命令升級(jí)所有可以升級(jí)的(過時(shí)的)包,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • python 接口測(cè)試response返回?cái)?shù)據(jù)對(duì)比的方法

    python 接口測(cè)試response返回?cái)?shù)據(jù)對(duì)比的方法

    本篇文章主要介紹了python 接口測(cè)試response返回?cái)?shù)據(jù)對(duì)比的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-02-02
  • 卸載tensorflow-cpu重裝tensorflow-gpu操作

    卸載tensorflow-cpu重裝tensorflow-gpu操作

    這篇文章主要介紹了卸載tensorflow-cpu重裝tensorflow-gpu操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • 解決tensorboard多個(gè)events文件顯示紊亂的問題

    解決tensorboard多個(gè)events文件顯示紊亂的問題

    今天小編就為大家分享一篇解決tensorboard多個(gè)events文件顯示紊亂的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • python 裝飾器功能與用法案例詳解

    python 裝飾器功能與用法案例詳解

    這篇文章主要介紹了python 裝飾器功能與用法,結(jié)合具體實(shí)例形式詳細(xì)分析了python 裝飾器的基本原理、功能、用法及操作注意事項(xiàng)
    2020-03-03
  • python分布式庫celery處理大規(guī)模的任務(wù)并行化

    python分布式庫celery處理大規(guī)模的任務(wù)并行化

    Python中的分布式任務(wù)隊(duì)列時(shí),Celery是一個(gè)備受推崇的工具,它是一個(gè)功能強(qiáng)大的分布式系統(tǒng),可用于處理大規(guī)模的任務(wù)并行化,本文將介紹Celery的基本概念、用法和示例代碼,幫助讀者更好地了解和使用這個(gè)庫
    2024-01-01
  • Python利用模糊哈希實(shí)現(xiàn)對(duì)比文件相似度

    Python利用模糊哈希實(shí)現(xiàn)對(duì)比文件相似度

    對(duì)比兩個(gè)文件相似度,python中可通過difflib.SequenceMatcher/ssdeep/python_mmdt/tlsh實(shí)現(xiàn),<BR>在大量需要對(duì)比,且文件較大時(shí),需要更高的效率,可以考慮模糊哈希,本文就來和大家詳細(xì)聊聊
    2023-01-01
  • python?中的np.zeros()和np.ones()函數(shù)詳解

    python?中的np.zeros()和np.ones()函數(shù)詳解

    這篇文章主要介紹了python?中的np.zeros()和np.ones()函數(shù),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04
  • python的flask框架難學(xué)嗎

    python的flask框架難學(xué)嗎

    在本篇內(nèi)容中小編給大家分享了關(guān)于python的flask框架是否難學(xué)的相關(guān)知識(shí)點(diǎn),有興趣的朋友們閱讀下吧。
    2020-07-07

最新評(píng)論