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

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

匹配 match case 变量 967    来源:    2025-03-15

在Python 3.10中引入了match-case语句,它提供了一种结构化的模式匹配方式。虽然match-case语句主要用于匹配单个变量的值,但你可以通过嵌套或组合模式来同时匹配多个变量的值。

示例:同时匹配多个变量的值

假设你有两个变量xy,你想同时匹配它们的值。你可以通过以下方式实现:

def match_multiple_variables(x, y):
    match (x, y):
        case (1, 2):
            print("x is 1 and y is 2")
        case (3, 4):
            print("x is 3 and y is 4")
        case (_, _):
            print("x and y are something else")

# 测试
match_multiple_variables(1, 2)  # 输出: x is 1 and y is 2
match_multiple_variables(3, 4)  # 输出: x is 3 and y is 4
match_multiple_variables(5, 6)  # 输出: x and y are something else

解释:

  • match (x, y)::将xy作为一个元组进行匹配。
  • case (1, 2)::匹配x为1且y为2的情况。
  • case (3, 4)::匹配x为3且y为4的情况。
  • case (_, _)::匹配所有其他情况,_是一个通配符,表示任意值。

更复杂的匹配

你还可以在case中使用更复杂的模式,例如匹配列表、字典等数据结构。

def match_complex_pattern(data):
    match data:
        case {"name": name, "age": age}:
            print(f"Name: {name}, Age: {age}")
        case [x, y, z]:
            print(f"List with three elements: {x}, {y}, {z}")
        case _:
            print("Unknown pattern")

# 测试
match_complex_pattern({"name": "Alice", "age": 30})  # 输出: Name: Alice, Age: 30
match_complex_pattern([1, 2, 3])  # 输出: List with three elements: 1, 2, 3
match_complex_pattern("Hello")  # 输出: Unknown pattern

总结

通过将多个变量组合成一个元组或使用复杂的数据结构,你可以在match-case语句中同时匹配多个变量的值。这种方式使得模式匹配更加灵活和强大。