文章目录
在 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
那样进行复杂的模式匹配。
- 匹配模式相对受限,一般只能进行常量值的比较,无法像 Python 的
穿透特性
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
语句则相对简单,主要用于常量值的比较。