match语法

需要python3.9以上版本支持

    ts=(0,5)
    match ts:
        case '5':
            print('5')
        case '8':
            print('8')
        case 9:
            print('9')
        case 401 | 403 | 404:
            print('or')
        case (0,0):
            print('Origin')
        case (0,y):
            print("y=",y)
        case (x,y):
            print(x,y)
        case _:
            print('default')

集合、元组

def match_sequence(seq):
    match seq:
        case []:
            print("序列为空")
        case [a]:
            print(f"序列只有一个元素:")
        case [x, y]:
            print(f"序列有两个元素,[, ]")
        case [b, 1]:
            print(f"序列有两个元素,第一个元素为 ")
        case [_, _, c]:
            print(f"序列有三个元素,第三个元素为 ")
        case _:
            print(f"序列未知")


match_sequence([])                # 序列为空
match_sequence([2])               # 序列只有一个元素:2
match_sequence([4, 1])            # 序列有两个元素,[4, 1]
match_sequence([1, 2, 3])         # 序列有三个元素,第三个元素为 3
match_sequence([1, 2, 3, 4, 5])   # 序列未知

集全高级用法

def match_sequence2(seq):
    match seq:
        case [1, *p]:
            print(p)
        case [3, a, *_]:
            print(f"a=")
        case [_, _, *q]:
            print(q)


match_sequence2([1, 2, 3, 4])    # [2, 3, 4]
match_sequence2([3, 4, 5, 6])    # a=4
match_sequence2([2, 3, 4, 5])    # [4, 5]

匹配字典

def match_dict(d):
    match d:
        case {"name": name, "age": age}:
            print(f"name=,age=")
        case {"key": _, "value": value}:
            print(f"value=")
        case {"first": _, **rest}:
            print(rest)
        case _:
            pass


d1 = {"name": "ice", "age": 18}
d2 = {"key": "k", "value": "v"}
d3 = {"first": "one", "second": "two", "third": "three"}

match_dict(d1)    # name=ice,age=18
match_dict()      # value=v
match_dict(d3)    # {'second': 'two', 'third': 'three'}

其它用法

https://blog.csdn.net/dreaming_coder/article/details/131418193