match subject: case <pattern_1>: <action_1> case <pattern_2>: <action_2> case <pattern_3>: <action_3> case _: <action_wildcard> 最后的case _:相当于if-elif最后的else,它能匹配任何值。 匹配标量 所谓标量就是常量,以及当做常量使用的枚举值。 注意:变量是不能作为case后面的匹配值使用的。
假设我们正在编写一些代码来将 HTTP 状态代码转换为错误消息,我们可以使用 match-case 语法如下: 事实上,对于这个特定的例子,match-case 没有比 if-else 语法带来任何好处,如下所示。 def http_error(status): if status == 400: return "Bad request" elif status == 401: return "Unauthorized" elif status...
)match-case 匹配类型和结构 Python 的另一个令人难以置信的功能是能够匹配类型和结构。这意味着 Python 可以判断一个对象是否是可迭代的,可以从中提取值,检查传入的内容的类型。values=['zbxx.net']match values: case [a]: print(f'只有一个元素:{a}') case [a, b]: print(f'两个元素...
有了match case之后,我们可以这样做匹配: 代码语言:python 代码运行次数:0 运行 AI代码解释 defselect_platform(name):matchname:case"小破站":print(f"程序员晚枫的{name}账号名称是:程序员晚枫")case"Z乎":print(f"程序员晚枫的{name}账号名称是:程序员晚枫")case"小红薯":print(f"程序员晚枫的{name}账号...
match ... case是 Python 3.10 中引入的一个新特性,也被称为“模式匹配”或“结构化匹配”。 它为Python 带来了更强大、更易读的分支控制,相比于传统的if-elif-else链。 基本模式匹配 x = 10 match x: case 10: print("x is 10") case 20: ...
Python在3.10.0版本中新增了match……case语句,它源自C语言中的switch……case语句,但具有更强大的使用方法。文中将对match……case语句的一些简单使用方法进行探索,首先给出了全部源代码,然后再对各个用法进行分析。 源代码 importsysdefbasic_usage(x):i=0match x:case1:i=1case2:i=2case3|4:i=3case _:...
match value: case 1: print("匹配到值为1") case 2: print("匹配到值为2") case _: print("匹配到其他值") match_example(1) # 输出: 匹配到值为1 match_example(2) # 输出: 匹配到值为2 match_example(3) # 输出: 匹配到其他值以上...
match subject: case<pattern_1>:<action_1>case<pattern_2>:<action_2>case<pattern_3>:<action_3>case _:<action_wildcard> match ... case 是 Python 3.10 中引入的一个新特性,也被称为“模式匹配”或“结构化匹配”。 1,基本模式匹配
match item:case['evening', action]: print(f'You almost finished the day! Now {action}')case[time, action]: print(f'Good {time} It is time to {action}')case_: print('default') alarm(['qwer']) alarm(['evening','work'])
事实上,对于这个特定的例子,match-case 没有比 if-else 语法带来任何好处,如下所示。 def http_error(status): if status == 400: return "Bad request" elif status == 401: return "Unauthorized" elif status == 403: return "Forbidden" elif status == 404: ...