在case的标量,也可以是多值,多值之间通过|分割(与C、JAVA的switch-case不同),例如: ... case 401|403|404: return "Not allowed" match-case只有OR模式,没有AND模式 匹配枚举 可以通过定义枚举值来进行条件匹配,match-case看上去是把枚举值当做标量来处理。 class Color(): RED = 1 GREEN = 2 BLUE = ...
, '2', '3']deftype_of(var): match var: case int() | float() as var:return"数值" case dict() as var:return"字典" case list() | tuple() | set() as var:return"列表,元组,集合" case str() as var:return"字符串" case _:return"其他类型"print(type_of(1)) ...
match/case 语句的匹配对象可以是映射。映射的的模式看似 dict 字面量,其实可以匹配collections.abc.Mapping的任何子类或虚拟子类。 示例:从匹配对象中提取作者 代码如下: def get_creators(record: dict) -> list: match record: case {'type': 'book', 'api': 2, 'authors': [*names]}: ❶ return na...
matchmy_list:case[0,1,2]:print('The list contains the values 0, 1, and 2')case[x,y,z]...
match-case是python3.10+的新特性,可以理解为python中的switch-case。如果你想要使用它,请注明所需python>=3.10. 基本语法和语义 match <表达式>: case <值1>: <语句块1> case <值2> | <值3> | <值4> : <语句块2> case _: <语句块3>
match ... case是 Python 3.10 中引入的一个新特性,也被称为“模式匹配”或“结构化匹配”。 它为Python 带来了更强大、更易读的分支控制,相比于传统的if-elif-else链。 基本模式匹配 x = 10 match x: case 10: print("x is 10") case 20: ...
match value: case 1: print("匹配到值为1") case 2: print("匹配到值为2") case _: print("匹配到其他值") match_example(1) # 输出: 匹配到值为1 match_example(2) # 输出: 匹配到值为2 match_example(3) # 输出: 匹配到其他值以上...
match item:case[time, action]: print(f'{time} {action}')case[time, *actions]:foractioninactions: print(f'^^ {time} {action}') alarm(['afternoon','work']) alarm(['morning',1,5,6]) def alarm(item: list): match item:case[('morning'|'afternoon'|'evening')astime, action]: ...
Python3.10.0正式版本在月初终于发布了,其中一个重要的特性就是支持match-case语句,这一类似C语言switch-case语句终于在Python中实现了。 一般匹配模式 C语言中一个典型的swicht-case语句像下面这样,在switch里包含要判断的变量x,case语句后则是匹配变量值是多少,如果满足这个匹配条件,就执行“case n:”后面的语句,...
from http import HTTPStatus import random http_status = random.choice(list(HTTPStatus)) match http_status: case 200 | 201 | 204 as status: # 👆 Using "as status" extracts its value print(f"Everything is good! {status = }") # 👈 Now status can be used inside handler case 400 ...