在Python 3.10中引入了match-case
语句,它提供了一种结构化的模式匹配方式。虽然match-case
语句主要用于匹配单个变量的值,但你可以通过嵌套或组合模式来同时匹配多个变量的值。
假设你有两个变量x
和y
,你想同时匹配它们的值。你可以通过以下方式实现:
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):
:将x
和y
作为一个元组进行匹配。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
语句中同时匹配多个变量的值。这种方式使得模式匹配更加灵活和强大。