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

Python match-case语句如何同时匹配多个变量的值?

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

在Python 3.10及以上版本中,match-case语句可以用来进行模式匹配。如果你想要同时匹配多个变量的值,可以使用元组(tuple)来组合这些变量,并在case语句中进行匹配。

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

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(3, 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 _: 是一个默认情况,匹配所有其他情况。

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