Match 條件判斷
Python 的 `match` 是 Python 3.10 引入的 **結構模式比對(Structural Pattern Matching)** 語法,功能類似其他語言的 `switch`,但也能比對資料結構。
## 基本語法
```python
match 表達式:
case 模式1:
# 符合模式1時執行
case 模式2:
# 符合模式2時執行
case _:
# 預設情況,類似 else
```
- `match`:指定要比對的值。
- `case`:定義比對條件。
- `_`:萬用字元,可匹配任何值。
- `case` 可以搭配 `if` 加入額外條件,稱為 guard。
## 範例 1:比對數字
```python
day = 2
match day:
case 1:
print("星期一")
case 2:
print("星期二")
case 3:
print("星期三")
case _:
print("其他日期")
```
輸出:
```text
星期二
```
也可以合併多個值:
```python
day = 6
match day:
case 6 | 7:
print("週末")
case _:
print("平日")
```
`|` 表示符合其中任一個模式。
## 範例 2:比對清單結構
```python
command = ["print", "Hello"]
match command:
case ["print", message]:
print(f"訊息:{message}")
case ["add", x, y]:
print(f"結果:{x + y}")
case _:
print("未知指令")
```
輸出:
```text
訊息:Hello
```
在 `["print", message]` 中,`message` 會接收清單第二個元素的值。
此外,也可以使用條件判斷:
```python
number = 8
match number:
case n if n > 0:
print("正數")
case 0:
print("零")
case _:
print("負數")
```
`match` 不是正規表示式(regex)的比對功能,而是用來比對值與資料結構。
相關學習地圖、教學課程
Python 資料工程
Python 後端工程、資料庫