类似于switch的语法,可以避免if else大量嵌套的情况,python3.10以上版本引入了match-case 同时match case还是一个非常强大的匹配语法 match case的基础语法是 mathc <表达式>: case <值1>: <代码1> case <值2>: <代码2> case <值3>|<值4>|<值5>: <代码3> case _: <代码5> 表达式的值依次匹配...
match-case的基本语法如下: match subject: case <pattern_1>: <action_1> case <pattern_2>: <action_2> case <pattern_3>: <action_3> case _: <action_wildcard> 最后的case _:相当于if-elif最后的else,它能匹配任何值。 匹配标量 所谓标量就是常量,以及当做常量使用的枚举值。 注意:变量是不能作...
有了match case之后,我们可以这样做匹配:defselect_platform(name): match name: case "小破站": print(f"程序员晚枫的{name}账号名称是:程序员晚枫") case "Z乎": print(f"程序员晚枫的{name}账号名称是:程序员晚枫") case "小红薯": print(f"程序员晚枫的{name}账号名称是:...
欢迎关注 @Python与数据挖掘 ,专注Python、数据分析、数据挖掘、好玩工具!最近发布的 Python 3.10 的所有主要新特性中最重要就是 Match-Case 语法。 有些人仍然认为 Python 不需要“switch-case”语法。 甚至 Gu…
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-case 匹配类型和结构 Python 的另一个令人难以置信的功能是能够匹配类型和结构。这意味着 Python 可以判断一个对象是否是可迭代的,可以从中提取值,检查传入的内容的类型。values=['zbxx.net']match values: case [a]: print(f'只有一个元素:{a}') case [a, b]: print(f'两个元素...
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 _:...
Python 3.10 has the match case which is Structural Pattern Matching. I'm going to show you what it can do with examples!
match-case是python3.10+的新特性,可以理解为python中的switch-case。如果你想要使用它,请注明所需python>=3.10. 基本语法和语义 match <表达式>: case <值1>: <语句块1> case <值2> | <值3> | <值4> : <语句块2> case _: <语句块3>