python学习-march模式匹配

部署运行你感兴趣的模型镜像

Python 3.11 引入了一个新特性,称为“结构化模式匹配”(Structured Pattern Matching),它受到了 Haskell 和 Rust 等语言中的模式匹配特性的启发。这个特性允许开发者使用更简洁和可读性更强的语法来处理不同的情况,类似于 switch-case 语句在其他语言中的作用。
以下是 Python 3.11 中模式匹配的基本语法和使用示例:

基本语法

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    # ...
    case _:
        <default_action>

示例

下面的示例展示了如何使用模式匹配来处理不同类型的输入:

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"
# 使用模式匹配
result = http_error(404)
print(result)  # 输出: Not found

模式匹配的类型

  1. 字面量模式:直接匹配字面量值。
match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Y={y}")
    case (x, 0):
        print(f"X={x}")
    case (x, y):
        print(f"X={x}, Y={y}")
  1. 捕获模式:可以捕获匹配到的值。
match point:
    case (x, 0):
        print(f"X axis, X={x}")
    case (0, y):
        print(f"Y axis, Y={y}")
    case (x, y):
        print(f"Neither axis, X={x}, Y={y}")
  1. 常量模式:匹配特定的常量值。
match point:
    case (0, 0):
        print("Origin")
    case (_, 0):
        print("On the x axis")
    case (0, _):
        print("On the y axis")
    case (_, _):
        print("Somewhere else")
  1. 序列和映射模式:可以用来匹配序列(如列表、元组)和映射(如字典)。
match point:
    case [x, y]:
        print(f"List: X={x}, Y={y}")
    case (x, y):
        print(f"Tuple: X={x}, Y={y}")
    case {"x": x, "y": y}:
        print(f"Dictionary: X={x}, Y={y}")
  1. 类模式:可以匹配类的实例,并且可以提取属性。
class Point:
    x: int
    y: int
def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
p = Point()
p.x = 10
p.y = 20
where_is(p)  # 输出: Somewhere else

结构化模式匹配是一个强大的新特性,使得处理复杂的数据结构更加简洁和直观。

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Qhumaing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值