目录
- 专栏列表
- 前言
- 基本语法
- match 语句
- case 语句
 
- 模式匹配的类型
- 示例
- 具体值匹配
- 类型匹配
- 序列匹配
- 星号表达式
- 命名变量
- 复杂匹配
 
- 模式匹配的优势
- 总结
 
专栏列表
- Python教程(一):环境搭建及PyCharm安装
- Python 教程(二):语法与数据结构
- Python 教程(三):字符串特性大全
- Python 教程(四):Python运算符合集
- Python 教程(五):理解条件语句和循环结构
- Python 教程(六):函数式编程
- Python 教程(七):match…case 模式匹配

正文开始,如果觉得文章对您有帮助,请帮我三连+订阅,谢谢💖💖💖
前言
在 Python 中,match 和 case 是一种新的语法结构,首次出现在 Python 3.10 中。这种结构提供了一种类似于其他编程语言中 switch 或 case 的功能,允许基于不同条件执行不同的代码块。
基本语法
match 语句
match 语句是 Python 中的模式匹配语句,它允许你将一个值与多个模式进行匹配,并根据匹配结果执行相应的代码块。
match value:
    case pattern1:
        code_block1
    case pattern2:
        code_block2
    ...
    case _:
        default_code_block
case 语句
case 语句是 match 语句的一部分,用于定义一个或多个模式,当 match 语句中的值与这些模式匹配时,将执行相应的代码块。
模式匹配的类型
- 具体值匹配:匹配一个具体的值。
- 类型匹配:匹配一个特定的数据类型。
- 序列匹配:匹配一个序列,例如列表或元组。
- 星号表达式:匹配序列中的部分元素。
- 命名变量:在模式中使用变量名,将匹配的值赋给这些变量。
- 复杂匹配: 可以匹配多个值、匹配一定范围,并且把匹配后的值绑定到变量
示例
具体值匹配
某个学生的成绩只能是 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.

模式匹配的优势
- 代码可读性:模式匹配使得代码更易于理解和维护。
- 减少嵌套:可以减少 if-elif-else语句的嵌套,使代码更简洁。
- 类型安全:通过类型匹配,可以确保变量的类型正确,减少类型错误。
总结
match 和 case 是 Python 3.10 中引入的新特性,它们提供了一种强大且灵活的方式来处理条件逻辑。通过学习这些特性,你可以编写更清晰、更高效的代码。希望本教程能帮助你更好地理解和使用这些新特性。如果你有任何问题或需要进一步的帮助,请随时联系我们。
















![[0729] X-CMD 发布 v0.4.3:借助 fzf ,提升用户使用体验](https://i-blog.csdnimg.cn/direct/d3c3bc748a5b4fa8878de603f26e5cc7.png#pic_center)


