Pythonでmatch文によるパターンマッチング (Python 3.10以降)
Python 3.10以降で導入されたmatch文によるパターンマッチングの解説です。match文の構文、基本的な使い方、タプルやリスト、辞書などのデータ構造への適用方法、そして実践的な例を通して理解を深めます。
目次
match文の基本構文
match文の基本的な構文はcase文で構成され、条件式と実行する処理を記述します。
status_code = 200
match status_code:
case 200:
print("Success!")
case 404:
print("Not Found")
case 500:
print("Internal Server Error")
case _:
print("Other error")
上記の例では、status_codeの値に応じて異なる処理が実行されます。'_' はワイルドカードパターンで、どのcaseにもマッチしない場合に実行されます。
リテラルパターン
リテラルパターンは、特定の値と比較します。
point = (1, 2)
match point:
case (1, 2):
print("Point is (1, 2)")
case (0, 0):
print("Point is (0, 0)")
case _:
print("Other point")
タプルやリストなど、複数の値を持つデータ構造にも使用できます。
変数パターン
変数パターンは、値を任意の変数に束縛します。
data = 10
match data:
case x:
print(f"The value is: {x}")
変数パターンを使用すると、値を変数に格納して、後続の処理で使用できます。
ワイルドカードパターン
ワイルドカードパターン '_' は、任意の値にマッチします。
data = 20
match data:
case 10:
print("data is 10")
case _:
print("data is not 10")
エラー処理やデフォルトの動作を定義する際に便利です。
シーケンスパターン
シーケンスパターンは、タプルやリストなどのシーケンスデータとマッチします。
data = [1, 2, 3]
match data:
case [1, 2, x]:
print(f"The third element is: {x}")
case [x, y, z]:
print(f"The elements are: {x}, {y}, {z}")
case _:
print("Other sequence")
要素の数や、特定の要素の値を指定してマッチングできます。
マッピングパターン
マッピングパターンは、辞書などのマッピングデータとマッチします。
data = {"name": "Alice", "age": 30}
match data:
case {"name": name, "age": age}:
print(f"Name: {name}, Age: {age}")
case _:
print("Other mapping")
キーと値を指定してマッチングできます。
ガード節付きパターン
ガード節は、パターンマッチに加えて、追加の条件式を指定できます。
point = (3, 4)
match point:
case (x, y) if x * x + y * y == 25:
print("Point is on the circle")
case (x, y):
print(f"Point is ({x}, {y})")
条件式がTrueの場合にのみマッチします。
実践的な例
より複雑なデータ構造や、複数の条件を組み合わせたパターンマッチングの例を示します。
data = ["apple", 10, {"color": "red"}]
match data:
case [fruit, count, {"color": color}] if count > 5:
print(f"We have {count} {fruit}s, and their color is {color}")
case _:
print("Other data")
パターンマッチングは、データの構造や内容に基づいて、柔軟で可読性の高いコードを書くのに役立ちます。
関連記事
- Pythonで文字列が特定のパターンに一致するか判定(正規表現, re.match, re.search, re.fullmatch)
- Pythonでif文による条件分岐
- Pythonでfor文によるループ処理(for in, for in range)
- Pythonでwhile文によるループ処理
- Pythonでラムダ式(無名関数)を使う(lambda)
- Pythonで関数を定義(def)
- Pythonで高階関数を使う(map, filter, reduceなど)
- Pythonでtry-except文による例外処理
- Pythonで関数に型ヒントをつける (Python 3.5以降)
- Pythonで可変長引数を使う(*args, **kwargs)