”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Python 中的结构模式匹配

Python 中的结构模式匹配

发布于2024-11-09
浏览:438

Structural pattern matching in Python

结构模式匹配是Python中的一个强大功能,它允许您根据复杂数据的结构做出决策并从中提取所需的值。它提供了一种简洁、声明式的方式来表达条件逻辑,可以极大地提高代码的可读性和可维护性。在本文中,我们将探讨一些在 Python 中使用结构模式匹配的真实案例研究示例。

1。解析 API 响应
结构模式匹配的一种常见用例是解析 API 响应。假设您正在使用一个天气 API,该 API 以以下格式返回数据:

{
  "current_weather": {
    "location": "New York",
    "temperature": 25,
    "conditions": "Sunny"
  }
}

要从此响应中提取温度,您可以使用结构模式匹配,如下所示:

response = {
  "current_weather": {
    "location": "New York",
    "temperature": 25,
    "conditions": "Sunny"
  }
}

match response:
    case {"current_weather": {"temperature": temp}}:
        print(f"The current temperature in {response['current_weather']['location']} is {temp} degrees Celsius.")
    case _:
        print("Invalid response.")

此模式匹配任何带有“current_weather”键的字典,并且在该键中,它匹配“温度”值并将其提取为变量 temp。这使您可以轻松访问所需的数据,而无需编写多个 if 语句来检查键是否存在。

2.数据处理
在处理大型数据集时,结构模式匹配也很有用。想象一下,您有一个数据集,其中包含有关不同产品的信息,包括它们的名称、类别和价格。您希望过滤数据集以仅包含低于特定价格阈值的产品。您可以使用模式匹配来提取所需的数据并对其进行过滤,如下所示:

products = [
  {"name": "Smartphone", "category": "Electronics", "price": 500},
  {"name": "T-shirt", "category": "Clothing", "price": 20},
  {"name": "Headphones", "category": "Electronics", "price": 100},
  {"name": "Jeans", "category": "Clothing", "price": 50},
]

match products:
    case [{"category": "Electronics", "price": price} for price in range(200)] as electronics:
        print([product["name"] for product in electronics])
    case [{"category": "Clothing", "price": price} for price in range(40)] as clothing:
        print([product["name"] for product in clothing])
    case _:
        print("No products found.")

在此示例中,模式根据类别和价格约束匹配并提取值。这允许使用更简洁和可读的方法来过滤数据集。

3.验证用户输入
结构模式匹配对于验证用户输入也很有用。想象一下,您正在为一个网站创建注册表单,并且您希望确保用户的电子邮件格式正确并且其密码满足某些要求。您可以使用模式匹配来执行这些验证,如下所示:

import re

email = "[email protected]"
password = "12345"

match email:
    case _ if not re.match(r"^\w @[a-zA-Z_] ?\.[a-zA-Z]{2,3}$", email):
        print("Invalid email format.")
    case _ if len(password) 



此模式使用正则表达式匹配并验证电子邮件格式,并使用长度检查来匹配和验证密码长度。这种方法可以轻松扩展,以根据需要包含额外的验证。

4。动态调度函数
结构模式匹配的另一个有趣的用例是根据输入参数动态调度函数。想象一下,您正在使用一个计算器程序,用户可以在其中输入一个运算和两个数字,该程序将为它们执行计算。您可以使用模式匹配根据指定的操作执行正确的函数,如下所示:

from operator import add, sub, mul, truediv as div

def calculate(operator, num1, num2):
    match operator:
        case " ":
            return add(num1, num2)
        case "-":
            return sub(num1, num2)
        case "*":
            return mul(num1, num2)
        case "/":
            return div(num1, num2)
        case _:
            print("Invalid operation.")

result = calculate("*", 5, 3)
print(f"The result is: {result}")
# Output: The result is: 15

该模式匹配指定的运算符并执行运算符模块中的相应函数。这提供了一种紧凑且可扩展的方法来处理不同的操作,而无需编写多个 if 语句。

结论
结构模式匹配是 Python 中的一项强大功能,可实现简洁、声明性和选择性代码。它可用于多种场景,从解析 API 响应到验证用户输入和动态调度函数。通过利用结构模式,您可以提高代码的可读性和可维护性,并使复杂的逻辑更易于管理。

版本声明 本文转载于:https://dev.to/myexamcloud/structural-pattern-matching-in-python-3em1?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3