Python match 文

Python3 条件控制Python3 条件制御


matchは Python 3.10 で導入された構造化パターンマッチング文であり、他の言語のswitch-case、ただし機能はより強力です。

match 文はデータ構造のパターンにマッチでき、定数値だけでなく、型、シーケンス、辞書などの複雑なパターンにもマッチします。

単語の意味: match「マッチ」という意味で、パターンマッチングに使用します。


基本構文とパラメータ

match 文は Python 3.10+ の新機能で、複雑な多分岐 if-elif 構造の代替として使用されます。

構文形式

match 变量:
    case 模式1:
        代码块1
    case 模式2:
        代码块2
    case _:
        默认代码块

パターンの種類

  • 定数パターン:具体的な値にマッチします。
  • ワイルドカードパターン: case _任意の値にマッチし、default に相当します。
  • 型パターン:データ型にマッチします。
  • シーケンスパターン:リスト、タプルなどのシーケンスにマッチします。
  • 辞書パターン:辞書にマッチします。
  • 条件付きパターン:使用if追加の条件を追加します。

例

例1:基本用法(switch に類似)

例

# Python バージョン要件 3.10+
def http_status(status):
    match status:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Server Error"
        case _:
            return "Unknown"

print(http_status(200))   # 出力: OK
print(http_status(404))   # 出力: Not Found
print(http_status(999))   # 出力: Unknown

期待される実行結果:

OK
Not Found
Unknown

コード解析:

  1. case _ワイルドカードであり、マッチしなかったすべてのケースにマッチします。
  2. switch-case の default に似ています。

例2:複数値のマッチング

例

# 複数の値を同じ結果にマッチ
def color_name(code):
    match code:
        case "r" | "R":
            return "赤色"
        case "g" | "G":
            return "緑色"
        case "b" | "B":
            return "青色"
        case _:
            return "未知"

print(color_name("r"))  # 出力: 赤色
print(color_name("G"))  # 出力: 緑色
print(color_name("x"))  # 出力: 未知
[/mycode]</div>
</div>

<p><strong>期待される実行結果:</strong></p>
<pre>赤色
緑色
未知
</pre>
<p>使用<code>|</code>複数の値を同じ case に組み合わせることができます。</p>
<h3>例3:シーケンスパターンマッチング</h3>

<div class="example">
<h2 class="example">例</h2>
<div class="example_code">[mycode4 type="python"]
# シーケンスパターンマッチング
def describe_point(point):
    match point:
        case (0, 0):
            return "原点"
        case (x, 0):
            return f"X軸上の点 ({x}, 0)"
        case (0, y):
            return f"Y軸上の点 (0, {y})"
        case (x, y):
            return f"平面上の点 ({x}, {y})"
        case _:
            return "無効な座標"

print(describe_point((0, 0)))      # 出力: 原点
print(describe_point((5, 0)))      # 出力: X軸上の点 (5, 0)
print(describe_point((3, 4)))      # 出力: 平面上の点 (3, 4)

期待される実行結果:

原点
X轴上的点 (5, 0)
平面上的点 (3, 4)

match はタプル/リストを分解して、その中の値を抽出できます。

例4:辞書パターンマッチング

例

# 辞書パターンマッチング
def process_user(user):
    match user:
        case {"name": name, "age": age}:
            return f"ユーザー: {name}, 年齢: {age}"
        case {"name": name}:
            return f"ユーザー: {name}"
        case _:
            return "無効なユーザー"

print(process_user({"name": "Tom", "age": 20}))
print(process_user({"name": "Jerry"}))
print(process_user({"role": "admin"}))

期待される実行結果:

ユーザー: Tom, 年龄: 20
ユーザー: Jerry
无效用户

辞書パターンは特定のキーの値を抽出できます。

例5:条件付きパターン

例

# 条件付きパターンマッチング
def classify_number(n):
    match n:
        case n if n > 0:
            return f"正の数 ({n})"
        case n if n < 0:
            return f"負の数 ({n})"
        case 0:
            return "ゼロ"

print(classify_number(10))   # 出力: 正の数 (10)
print(classify_number(-5))    # 出力: 負の数 (-5)
print(classify_number(0))     # 出力: ゼロ

# 複雑な条件
def describe_list(lst):
    match lst:
        case []:
            return "空のリスト"
        case [x]:
            return f"単一の要素: {x}"
        case [x, y]:
            return f"2つの要素: {x}, {y}"
        case [x, *rest]:
            return f"最初: {x}, 残り: {rest}"

print(describe_list([]))
print(describe_list([1]))
print(describe_list([1, 2, 3, 4]))

期待される実行結果:

正数 (10)
负数 (-5)
零
空列表
单个元素: 1
第一个: 1, 其余: [2, 3, 4]

使用case 变量 if 条件追加のマッチング条件を追加できます。


Python3 条件控制Python3 条件制御

その他の拡張