在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):
将x
和y
组合成一个元组进行匹配。case (0, 0):
匹配x
和y
都为0
的情况。case (0, _):
匹配x
为0
,y
为任意值的情况。_
是一个通配符,表示任意值。case (_, 0):
匹配y
为0
,x
为任意值的情况。case (1, 1):
匹配x
和y
都为1
的情况。case _:
是一个默认情况,匹配所有其他情况。通过这种方式,你可以同时匹配多个变量的值,并根据不同的组合执行相应的代码块。