插件窝 干货文章 Python3.10 match-case语句:如何同时匹配多个变量的值?

Python3.10 match-case语句:如何同时匹配多个变量的值?

匹配 match case variables 208    来源:    2025-03-13

在Python 3.10中引入了match-case语句,类似于其他语言中的switch-case语句,但功能更强大。match-case语句允许你根据模式匹配来执行不同的代码块。

如果你想要同时匹配多个变量的值,可以使用元组(tuple)来组合这些变量,并在match语句中进行匹配。

以下是一个示例,展示了如何同时匹配多个变量的值:

def match_multiple_variables(x, y):
    match (x, y):
        case (0, 0):
            print("Both x and y are 0")
        case (0, _):
            print("x is 0, y is something else")
        case (_, 0):
            print("y is 0, x is something else")
        case (1, 1):
            print("Both x and y are 1")
        case _:
            print("Neither x nor y match the specific cases")

# 测试
match_multiple_variables(0, 0)    # 输出: Both x and y are 0
match_multiple_variables(0, 5)    # 输出: x is 0, y is something else
match_multiple_variables(5, 0)    # 输出: y is 0, x is something else
match_multiple_variables(1, 1)    # 输出: Both x and y are 1
match_multiple_variables(2, 3)    # 输出: Neither x nor y match the specific cases

解释:

  • match (x, y):xy组合成一个元组进行匹配。
  • case (0, 0): 匹配xy都为0的情况。
  • case (0, _): 匹配x0y为任意值的情况。_是一个通配符,表示任意值。
  • case (_, 0): 匹配y0x为任意值的情况。
  • case (1, 1): 匹配xy都为1的情况。
  • case _: 是一个默认情况,匹配所有其他情况。

通过这种方式,你可以同时匹配多个变量的值,并根据不同的组合执行相应的代码块。