📜  match 语句 - Python (1)

📅  最后修改于: 2023-12-03 15:02:52.594000             🧑  作者: Mango

Match 语句 - Python

在 Python 3.10 中,新加入了 match 语句,可以用于更加优雅和清晰地编写多路分支逻辑。

基本用法

比如,我们需要实现一个返回数字对应的英文单词的函数:

def number_to_word(num: int) -> str:
    if num == 0:
        return "zero"
    elif num == 1:
        return "one"
    elif num == 2:
        return "two"
    else:
        return "unknown"

使用 match 语句,可以写作:

def number_to_word(num: int) -> str:
    match num:
        case 0:
            return "zero"
        case 1:
            return "one"
        case 2:
            return "two"
        case _:
            return "unknown"

代码更加紧凑,而且逻辑更加清晰明了。

匹配模式

match 语句可以和多种匹配模式一起使用,让代码更加灵活和强大。

类型匹配

可以用 case int: 的形式进行类型匹配:

match value:
    case int:
        print("an integer")
    case float:
        print("a float")
    case str:
        print("a string")
值匹配

可以用常量的形式进行值匹配:

match value:
    case "yes":
        print("affirmative")
    case "no": 
        print("negative")
    case "maybe":
        print("uncertain")
星号匹配

可以用 case name *: 的形式进行星号匹配:

match value:
    case []:
        print("empty list")
    case [x]:
        print("a list with one item")
    case [x, y]:
        print("a list with two items")
    case [x, y, *rest]:
        print("a list with at least three items")
变量绑定

可以用 case name as value: 形式进行变量绑定:

match value:
    case {"key": "value"} as d:
        print(f"a dictionary {d}")
    case x as i:
        print(f"an integer {i}")
总结

使用 match 语句可以让多路分支逻辑更加清晰和优雅。同时,配合多种匹配模式,可以让代码更加灵活和强大。但需要注意,match 语句仅在 Python 3.10 中才可用,旧版本的 Python 中并不支持。