在 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")
讓我們通過語法來看看它是如何工作的。
我們創(chuàng)建的函數接受一個名為 message 的參數。match 關鍵字接受一個對象來比較列出的案例。
在我們的示例中,match 關鍵字接收一個字符串列表,這是 message.split() 操作的結果。為了進一步說明,假設我們這樣調用函數:
greeting("hello")
該函數首先將這個字符串拆分為所有空格,并形成一個列表。對于上述輸入,匹配運算符將使用 ["hello"] 列表。然后它將列表與每個案例進行比較。我們的第一個案例是:
case ["hello"]
我們的輸入與此完全匹配,因此代碼在這種情況下繼續(xù)執(zhí)行。
輸出:
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")。
比較表達式變?yōu)?["hello", "George", "Johnson"]?,F在讓我們來看看每個案例。第一種情況失敗,因為比較表達式中有 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")
在此代碼段中,第二種情況將匹配并執(zhí)行,輸出為:
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 開發(fā)人員在創(chuàng)建分支案例時可以利用的強大工具。有了它,你可以可靠地檢查任何傳入變量的結構,并確保你不會嘗試訪問變量上不存在的內容。
重要在字典匹配中,即使輸入字典的屬性多于 case 指定的屬性,case 仍將匹配。
總之,新的“match...case”運算符是 Python 開發(fā)人員在創(chuàng)建分支案例時可以利用的強大工具。有了它,可以可靠地檢查任何傳入變量的結構,并確保不會嘗試訪問變量上不存在的內容。