在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 语法格式:parameter = "zbxx.net"match parameter: case first : do_something(first) case second : do_something(second) ... ... case n : do_something(n) case _ : nothing_matched_function()match-case 语句使用 match 关键字初始化并获取一个参数,然后使...
match x: case x if x > 5: print("x is greater than 5") case _: print("x is 5 or less")
# match-case的基本例子color=input("请输入需要查询的颜色:")matchcolor:case"red"|"红"|"红色":r,g,b=255,0,0case"green"|"绿"|"绿色":r,g,b=0,255,0case"yellow"|"黄"|"黄色":r,g,b=255,255,0case_:r,g,b=-1,-1,-1ifr>=0:print(f"{color}的颜色代码:#{r:02X}{g:02X}{b...
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 subject: case <pattern_1>: <action_1> case <pattern_2>: <action_2> case <pattern_3>: <action_3> case _: <action_wildcard> case _: 类似于 C 和 Java 中的 default:,当其他 case 都无法匹配时,匹配这条,保证永远会匹配成功。 def describe_number(n): match n: case 0: return ...
match/case 模式匹配功能,可以替换我们常用的if/elif/elif/.../else代码块,并且支持析构:一种更强大的拆包功能。模式匹配是一种强大的工具,借助析构可以处理 嵌套的映射和序列 等结构化记录。下面是从书本中整理借鉴的内容,供大佬们学习参考: 一、序列模式匹配 ...
match value: case 1: print("匹配到值为1") case 2: print("匹配到值为2") case _: print("匹配到其他值") match_example(1) # 输出: 匹配到值为1 match_example(2) # 输出: 匹配到值为2 match_example(3) # 输出: 匹配到其他值以上...
Python3.10.0正式版本在月初终于发布了,其中一个重要的特性就是支持match-case语句,这一类似C语言switch-case语句终于在Python中实现了。 一般匹配模式 C语言中一个典型的swicht-case语句像下面这样,在switch里包含要判断的变量x,case语句后则是匹配变量值是多少,如果满足这个匹配条件,就执行“case n:”后面的语句,...