搜尋
首頁後端開發Python教學在 Python 3.10 中使用'match...case”

在 Python 3.10 中使用'match...case”

「match...case」語法類似於其他物件導向語言中的 switch 語句,它旨在使結構與 case 的匹配更容易。

讓我們開始.

語法

「match...case」語法如下:

def greeting(message):
match message.split():
case ["hello"]:
print("this message says hello")
case ["hello", name]:
print("This message is a personal greeting to {name}")
case _:
print("The message didn’t match with anything")

讓我們透過語法來看看它是如何工作的。

我們建立的函數接受一個名為 message 的參數。 match 關鍵字接受一個物件來比較列出的案例。

在我們的範例中,match 關鍵字接收一個字串列表,這是 message.split() 操作的結果。為了進一步說明,假設我們這樣呼叫函數:

greeting("hello")

該函數首先將這個字串拆分為所有空格,並形成一個列表。對於上述輸入,匹配運算子將使用 ["hello"] 清單。然後它將列表與每個案例進行比較。我們的第一個案例是:

case ["hello"]

我們的輸入與此完全匹配,因此程式碼在這種情況下繼續執行。

輸出:

this message says hello

如果我們這樣呼叫函數會怎麼樣:greeting("hello George")?

使用該輸入,匹配運算子將使用 ["hello", "George"] 清單來比較所有案例。第一種情況,case“hello”,將不匹配,因為比較清單中有兩個元素,而不是一個。

結構匹配

匹配運算子匹配給定的表達式的結構,因此,由於case 表達式的長度,我們的第一個case 不匹配,即使比較表達式與列表中的第一個元素匹配。

第二種情況是 ["hello", name]。這就是我們的輸入匹配的情況。如果你沒有為 Python 提供一個文字值來匹配,它會將比較表達式中的任何值綁定到 case 表達式中的變數名稱。因此,在我們的範例中,name 將設定為 George。並且這種情況匹配(它有“hello”作為第一個元素,並且還有一個元素,它被綁定到name),所以輸出是:

This message is a personal greeting to George

現在讓我們嘗試像這樣調用函數:greeting("hello George Johnson")。

比較表達式變成 ["hello", "George", "Johnson"]。現在讓我們來看看每個案例。第一種情況失敗,因為比較表達式中有 3 個元素,而不是 1。第二種情況以同樣的方式失敗;第二種情況期望看到一個長度為 2 的列表,其中第一個元素是「hello」。第一個元素其實是“hello”,但比較表達式有3個元素,所以這個case不符。

剩下的唯一選項是下劃線大小寫,這是預設的匹配所有內容的大小寫。把它想像成 switch 語句中的預設情況。如果比較表達式與其他任何內容都不匹配,它將始終與 _ 情況匹配。

下劃線作為最後一種情況下的任何情況都不會運行,因為所有情況都將與下劃線情況相符。這類似於 if...else 中的 else 關鍵字。 _ 大小寫匹配所有內容,因為 Python 將 _ 識別為有效的變數名稱。所以就像我們匹配 case ["hello", name] 時,比較表達式將綁定到 _ name。在我們的特定情況下,_ 變數將保存值 ["hello", "George", "Johnson"]。

所以在我們最新的函數呼叫greeting("hello George Johnson")中,輸出將會是:

The message didn’t match with anything

進階用法

「match...case」語法是一個非常強大的工具,可用於比較許多不同的表達式和值。如果像我們在上面的範例中那樣比較列表,那麼可以使用更多的匹配功能。

在 case 表達式中,可以使用運算子將所有剩餘元素放入變數中。例如:

comparison_list = ["one", "two", "three"]
match comparison_list:
case [first]:
print("this is the first element: {first}")
case [first, *rest]:
print("This is the first: {first}, and this is the rest: {rest}")
case _:
print("Nothing was matched")

在此程式碼段中,第二種情況將匹配並執行,輸出為:

This is the first: one, and this is the rest: ["two", "three"]

還可以從兩個或多個結構中組合案例分支,如下所示:

match comparisonList:
 case [first] | [first, "two", "seven"]:
 print("this is the first element: {first}")
 case [title, "hello"] | ["hello", title]:
 print("Welcome esteemed guest {title}")
 case [first, *rest]:
 print("This is the first: {first}, and this is the rest: {rest}")
 case _:
 print("Nothing was matched")

第一種和第二種情況由幾個不同的表達式組成,比較表達式可以適合這些表達式以運行case 分支。這提供了一些靈活性來組合分支。

我們也會介紹字典的「match...case」文法。匹配運算子將檢查比較表達式是否包含 case 表達式中的屬性。例如:

comparisonDictionary = {
 "John": "boy",
 "Jack": "boy",
 "Jill": "girl",
 "Taylor": "girl"
}
match comparisonDictionary:
 case {"John": "boy", "Taylor": "boy"}:
 print("John and Taylor are both boys")
 case {"John": "boy", "Taylor": "girl"}:
 print("Taylor is a girl and John is a boy")
 case _:
 print("Nothing matches")

輸出:

Taylor is a girl and John is a boy

match 運算子將檢查輸入字典中是否存在 case 屬性,然後檢查值是否符合。

總之,新的「match...case」運算子是 Python 開發人員在建立分支案例時可以利用的強大工具。有了它,你可以可靠地檢查任何傳入變數的結構,並確保你不會嘗試存取變數上不存在的內容。

重要在字典匹配中,即使輸入字典的屬性多於 case 指定的屬性,case 仍將匹配。

總之,新的「match...case」運算子是 Python 開發人員在建立分支案例時可以利用的強大工具。有了它,可以可靠地檢查任何傳入變數的結構,並確保不會嘗試存取變數上不存在的內容。

以上是在 Python 3.10 中使用'match...case”的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:51CTO.COM。如有侵權,請聯絡admin@php.cn刪除
Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

陣列的同質性質如何影響性能?陣列的同質性質如何影響性能?Apr 25, 2025 am 12:13 AM

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

編寫可執行python腳本的最佳實踐是什麼?編寫可執行python腳本的最佳實踐是什麼?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy數組與使用數組模塊創建的數組有何不同?Numpy數組與使用數組模塊創建的數組有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模塊與Python中的數組有何關係?CTYPES模塊與Python中的數組有何關係?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器