Python 教程(七):match...case 模式匹配

专栏列表


在这里插入图片描述

正文开始如果觉得文章对您有帮助,请帮我三连+订阅,谢谢💖💖💖


前言

在 Python 中,matchcase 是一种新的语法结构,首次出现在 Python 3.10 中。这种结构提供了一种类似于其他编程语言中 switchcase 的功能,允许基于不同条件执行不同的代码块。

基本语法

match 语句

match 语句是 Python 中的模式匹配语句,它允许你将一个值与多个模式进行匹配,并根据匹配结果执行相应的代码块。

match value:
    case pattern1:
        code_block1
    case pattern2:
        code_block2
    ...
    case _:
        default_code_block

case 语句

case 语句是 match 语句的一部分,用于定义一个或多个模式,当 match 语句中的值与这些模式匹配时,将执行相应的代码块。

模式匹配的类型

  1. 具体值匹配:匹配一个具体的值。
  2. 类型匹配:匹配一个特定的数据类型。
  3. 序列匹配:匹配一个序列,例如列表或元组。
  4. 星号表达式:匹配序列中的部分元素。
  5. 命名变量:在模式中使用变量名,将匹配的值赋给这些变量。
  6. 复杂匹配: 可以匹配多个值、匹配一定范围,并且把匹配后的值绑定到变量

示例

具体值匹配

某个学生的成绩只能是 A、B、C,用if语句编写如下:

score = 'B'
if score == 'A':
    print('score is A.')
elif score == 'B':
    print('score is B.')
elif score == 'C':
    print('score is C.')
else:
    print('invalid score.')

用 match 进行改写

score = 'B'

match score:
    case 'A':
        print('score is A.')
    case 'B':
        print('score is B.')
    case 'C':
        print('score is C.')
    case _: # _表示匹配到其他任何情况
        print('score is ???.')

类型匹配

def match_type(value):
    match value:
        case int():
            print("这是一个整数")
        case float():
            print("这是一个浮点数")
        case str():
            print("这是一个字符串")
        case _:
            print("未知类型")

match_type(10)  # 输出:这是一个整数
match_type(3.14)  # 输出:这是一个浮点数
match_type("hello")  # 输出:这是一个字符串
match_type([1, 2, 3])  # 输出:未知类型

在这里插入图片描述

序列匹配

def match_sequence(value):
    match value:
        case [1, 2, 3]:
            print("匹配到 [1, 2, 3]")
        case (1, num):
            print("匹配到元组,第一个元素为 1",'第二个数', num)
        case [1, *rest]:
            print(f"匹配到以 1 开头的列表,其余元素为 {rest}")
        case _:
            print("匹配到其他值")

match_sequence([1, 2, 3])  # 输出:匹配到 [1, 2, 3]
match_sequence([1, 4, 5])  # 输出:匹配到以 1 开头的列表,其余元素为 [4, 5]
match_sequence((1, 2))  # 输出:匹配到元组,第一个元素为 1 第二个数 2
match_sequence("hello")  # 输出:匹配到其他值

在这里插入图片描述

星号表达式

def match_sequence(value):
    match value:
        case [1, *rest]:
            print(f"匹配到以 1 开头的列表,其余元素为 {rest}")
        case _:
            print("匹配到其他值")

match_sequence([1, 2, 3])  # 输出:匹配到以 1 开头的列表,其余元素为 [2, 3]
match_sequence([1, 4, 5])  # 输出:匹配到以 1 开头的列表,其余元素为 [4, 5]

在这里插入图片描述

命名变量

def match_named(value):
    match value:
        case (a, b):
            print(f"匹配到元组,第一个元素为 {a},第二个元素为 {b}")
        case {"name": name, "age": age}:
            print(f"匹配到字典,名字为 {name},年龄为 {age}")
        case _:
            print("匹配到其他值")

match_named((1, 2))  # 输出:匹配到元组,第一个元素为 1,第二个元素为 2
match_named({"name": "Alice", "age": 30})  # 输出:匹配到字典,名字为 Alice,年龄为 30
match_named([1, 2, 3])  # 输出:匹配到其他值

在这里插入图片描述

复杂匹配

age = 15

match age:
    case x if x < 10:
        print(f'< 10 years old: {x}')
    case 10:
        print('10 years old.')
    case 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18:
        print('11~18 years old.')  
    case 19:
        print('19 years old.')
    case _:
        print('not sure.')


# 11~18 years old.

在这里插入图片描述

模式匹配的优势

  1. 代码可读性:模式匹配使得代码更易于理解和维护。
  2. 减少嵌套:可以减少 if-elif-else 语句的嵌套,使代码更简洁。
  3. 类型安全:通过类型匹配,可以确保变量的类型正确,减少类型错误。

总结

matchcase 是 Python 3.10 中引入的新特性,它们提供了一种强大且灵活的方式来处理条件逻辑。通过学习这些特性,你可以编写更清晰、更高效的代码。希望本教程能帮助你更好地理解和使用这些新特性。如果你有任何问题或需要进一步的帮助,请随时联系我们。

  • 49
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 41
    评论
评论 41
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

子羽bro

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

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

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

打赏作者

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

抵扣说明:

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

余额充值