[Python]条件分岐[match文]

Pythonでmatch文を用いて分岐処理を行うためのサンプルコード一覧

value パターン

value = "red"
match value:
    case "red":
        print("R")
    case "blue":
        print("B")
    case "green":
        print("G")

ワイルドカード パターン

value = input()
match value:
    case _:
        print("all")

ガード パターン

value = input()
match value:
    case x if x > 0:
        print("True")
    case y if y = 0:
        print("0")

type パターン

value = int(input())
match value:
    case int:
        print("int")
    case float:
        print("float")
    case str:
        print("str")
    case _:
        print("???")

as パターン

value = int(input())
match value:
    case int as n:
        print("int:", n)
    case float as f:
        print("float", f)
    case str as s:
        print("str", s)
    case _:
        print("???")

or パターン

value = int(input())
match value:
    case 0 or 1:
        print("value is either 0 or 1")
    case 2 or 3:
        print("value is either 2 or 3")
    case _:
        print("value is something else")

list パターン

match my_list:
    case [0, 1]:
        print("my_list is [0, 1]")
    case [2, 3]:
        print("my_list is [2, 3]")
    case [4, _, _]:
        print("my_list starts with 4 and has at least 3 elements")
    case _:
        print("my_list is something else")

tuple パターン

match my_tuple:
    case (0, 1):
        print("my_tuple is (0, 1)")
    case (2, 3):
        print("my_tuple is (2, 3)")
    case (4, _, _):
        print("my_tuple starts with 4 and has at least 3 elements")
    case _:
        print("my_tuple is something else")

dict パターン

match my_dict:
    case {'a': 1, 'b': 2}:
        print("my_dict is {'a': 1, 'b': 2}")
    case {'c': 3, 'd': 4}:
        print("my_dict is {'c': 3, 'd': 4}")
    case {'e': 5, 'f': _}:
        print("my_dict has the key 'e' with the value 5 and the key 'f' with some other value")
    case _:
        print("my_dict is something else")

class パターン

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

match my_obj:
    case MyClass(0, 1):
        print("my_obj is an instance of MyClass with x=0 and y=1")
    case MyClass(2, 3):
        print("my_obj is an instance of MyClass with x=2
タイトルとURLをコピーしました