match-case 语句使用 match 关键字初始化并获取一个参数,然后使用 case 关键字与参数匹配。“_”是通配符,当没有任何匹配项时运行。match-case 实例:day=input("请输入一个数字(1 - 7):")match day: case "1": print("星期一") case "2": print("星期二") case "3": print...
根据月份返回对应的季节 defget_season(month: int) -> Season: # 使用match-case结构匹配不同的...
case Point(x=x, y=0): print(f"Point is on the X axis at {x}") case Point(x, y): print(f"Point is at ({x}, {y})") case _: print("Not a point") OR 模式 使用| 来表示一个或多个模式。 x = 2 match x: case 1 | 2 | 3: print("x is 1, 2, or 3") case _:...
在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 = ...
match-case是python3.10+的新特性,可以理解为python中的switch-case。如果你想要使用它,请注明所需python>=3.10. 基本语法和语义 match <表达式>: case <值1>: <语句块1> case <值2> | <值3> | <值4> : <语句块2> case _: <语句块3>
matchcomparisonList:case[first]|[first,"two","seven"]:print("this is the first element: {first}")case[title,"hello"]|["hello",title]:print("Welcome esteemed guest {title}")case[first,*rest]:print("This is the first: {first}, and this is the rest: {rest}")case_:print("Nothing...
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]: ...
match item: case (x, y) if x == y: print(f"匹配到相等的元组: {item}") case (x, y): print(f"匹配到元组: {item}") case _: print("匹配到其他情况") match_example((1, 1)) # 输出: 匹配到相等的元组: (1, 1) match_example((1, 2)) # 输出: 匹配到元组: (1, 2) match...
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 _:...
Python3.10.0正式版本在月初终于发布了,其中一个重要的特性就是支持match-case语句,这一类似C语言switch-case语句终于在Python中实现了。 一般匹配模式 C语言中一个典型的swicht-case语句像下面这样,在switch里包含要判断的变量x,case语句后则是匹配变量值是多少,如果满足这个匹配条件,就执行“case n:”后面的语句,...