python 中match...case 和 C switch case区别

文章目录

在 Python 3.10 及以后的版本中引入了 match...case 语句,它和其他编程语言里的 switch...case 语句有相似之处,但也存在不少区别,

语法结构

  • match...case(Python)
    • match 语句后面紧跟一个需要匹配的表达式,然后通过一系列 case 子句来定义匹配模式和对应的操作。case 子句可以使用多种模式,如常量、变量、序列、映射等。
    • 示例代码如下:
python 复制代码
def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 401 | 403:
            return "Not allowed"
        case 404:
            return "Not found"
        case _:
            return "Something else"


print(http_error(404))
  • switch...case(以 C 语言为例)
    • switch 后面是一个控制表达式,通常是整数类型或者枚举类型。case 子句后面只能跟常量表达式,用于和控制表达式的值进行比较。每个 case 子句结束时一般需要使用 break 语句来跳出 switch 结构,否则会发生穿透现象。
    • 示例代码如下:
c 复制代码
#include <stdio.h>

void http_error(int status) {
    switch (status) {
        case 400:
            printf("Bad request\n");
            break;
        case 401:
        case 403:
            printf("Not allowed\n");
            break;
        case 404:
            printf("Not found\n");
            break;
        default:
            printf("Something else\n");
    }
}

int main() {
    http_error(404);
    return 0;
}

匹配模式的灵活性

  • match...case(Python)
    • 具有非常高的灵活性,支持多种复杂的匹配模式。除了常量匹配,还能进行序列匹配、映射匹配、类型匹配等。
    • 示例代码如下:
python 复制代码
def describe_person(person):
    match person:
        case {"name": name, "age": age} if age < 18:
            return f"{name} is a minor."
        case {"name": name, "age": age}:
            return f"{name} is an adult."
        case _:
            return "Unknown input."


print(describe_person({"name": "Alice", "age": 25}))
  • switch...case(其他语言)
    • 匹配模式相对受限,一般只能进行常量值的比较,无法像 Python 的 match...case 那样进行复杂的模式匹配。

穿透特性

  • match...case(Python)
    • 不存在穿透现象。当某个 case 子句匹配成功后,会执行该子句下的代码块,然后直接跳出 match 语句,不会继续执行后续的 case 子句。
  • switch...case(其他语言)
    • 若没有使用 break 语句,会发生穿透现象,即匹配成功一个 case 子句后,会继续执行后续 case 子句的代码,直到遇到 break 或者 switch 语句结束。

缺省情况处理

  • match...case(Python)
    • 使用 case _ 来表示缺省情况,类似于其他语言中的 default 子句。当所有 case 子句都不匹配时,会执行 case _ 子句下的代码。
  • switch...case(其他语言)
    • default 子句来处理缺省情况,当控制表达式的值与所有 case 子句中的常量都不匹配时,会执行 default 子句下的代码。

综上所述,Python 的 match...case 语句在语法和功能上都更加灵活强大,能够处理复杂的匹配需求,而传统的 switch...case 语句则相对简单,主要用于常量值的比较。

相关推荐
杨超越luckly1 小时前
Python应用指南:利用高德地图API获取POI数据(关键词版)
大数据·python·数据挖掘·数据分析·html
九亿AI算法优化工作室&2 小时前
SA模拟退火算法优化高斯回归回归预测matlab代码
人工智能·python·算法·随机森林·matlab·数据挖掘·模拟退火算法
Blossom.1182 小时前
基于Python的机器学习入门指南
开发语言·人工智能·经验分享·python·其他·机器学习·个人开发
郝YH是人间理想3 小时前
Python面向对象
开发语言·python·面向对象
藍海琴泉3 小时前
蓝桥杯算法精讲:二分查找实战与变种解析
python·算法
mqwguardain7 小时前
python常见反爬思路详解
开发语言·python
_庄@雅@丽7 小时前
(UI自动化测试web端)第二篇:元素定位的方法_xpath扩展(工作当中用的比较多)
python·ui自动化元素定位·xpath元素定位
测试笔记(自看)8 小时前
Python+Requests+Pytest+YAML+Allure接口自动化框架
python·自动化·pytest·allure
珊瑚里的鱼9 小时前
第三讲 | C/C++内存管理完全手册
c语言·c++·笔记·程序人生·visualstudio·visual studio