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

Python3.10 match-case语句如何高效匹配多个变量的值?

match 匹配 case zero 340    来源:    2025-03-14

在Python 3.10中引入了match-case语句,它提供了一种结构化的模式匹配方式,类似于其他语言中的switch-case语句。match-case语句可以高效地匹配多个变量的值,并且支持复杂的模式匹配。

基本用法

match-case语句的基本语法如下:

match value:
    case pattern1:
        # 处理 pattern1
    case pattern2:
        # 处理 pattern2
    case _:
        # 默认情况

匹配多个变量的值

如果你需要同时匹配多个变量的值,可以将这些变量组合成一个元组或列表,然后在case语句中进行匹配。

示例1:匹配元组

def match_multiple_values(x, y):
    match (x, y):
        case (0, 0):
            print("Both x and y are zero")
        case (0, _):
            print("x is zero, y is non-zero")
        case (_, 0):
            print("y is zero, x is non-zero")
        case _:
            print("Both x and y are non-zero")

# 测试
match_multiple_values(0, 0)  # 输出: Both x and y are zero
match_multiple_values(0, 5)  # 输出: x is zero, y is non-zero
match_multiple_values(5, 0)  # 输出: y is zero, x is non-zero
match_multiple_values(5, 5)  # 输出: Both x and y are non-zero

示例2:匹配列表

def match_list(values):
    match values:
        case [0, 0]:
            print("Both elements are zero")
        case [0, _]:
            print("First element is zero, second is non-zero")
        case [_, 0]:
            print("Second element is zero, first is non-zero")
        case _:
            print("Both elements are non-zero")

# 测试
match_list([0, 0])  # 输出: Both elements are zero
match_list([0, 5])  # 输出: First element is zero, second is non-zero
match_list([5, 0])  # 输出: Second element is zero, first is non-zero
match_list([5, 5])  # 输出: Both elements are non-zero

复杂模式匹配

match-case还支持更复杂的模式匹配,例如匹配字典、类实例等。

示例3:匹配字典

def match_dict(data):
    match data:
        case {"name": name, "age": age}:
            print(f"Name: {name}, Age: {age}")
        case {"name": name}:
            print(f"Name: {name}, Age unknown")
        case _:
            print("Invalid data format")

# 测试
match_dict({"name": "Alice", "age": 30})  # 输出: Name: Alice, Age: 30
match_dict({"name": "Bob"})  # 输出: Name: Bob, Age unknown
match_dict({"age": 25})  # 输出: Invalid data format

示例4:匹配类实例

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def match_class_instance(obj):
    match obj:
        case Point(x=0, y=0):
            print("Point at origin")
        case Point(x=0, y=y):
            print(f"Point on y-axis at y={y}")
        case Point(x=x, y=0):
            print(f"Point on x-axis at x={x}")
        case Point(x=x, y=y):
            print(f"Point at ({x}, {y})")
        case _:
            print("Not a Point object")

# 测试
match_class_instance(Point(0, 0))  # 输出: Point at origin
match_class_instance(Point(0, 5))  # 输出: Point on y-axis at y=5
match_class_instance(Point(5, 0))  # 输出: Point on x-axis at x=5
match_class_instance(Point(5, 5))  # 输出: Point at (5, 5)
match_class_instance("Not a Point")  # 输出: Not a Point object

总结

通过match-case语句,你可以高效地匹配多个变量的值,并且支持复杂的模式匹配。你可以将多个变量组合成元组、列表、字典或类实例,然后在case语句中进行匹配。这种方式不仅代码简洁,而且可读性强,非常适合处理复杂的条件分支逻辑。