match-case的使用

Python实用教程_spiritx的博客-CSDN博客

python没有switch-case语句,但在Python 3.10 增加了 match-case 的条件判断,不需要再使用一连串的 if-else 来判断了,使用上比switch-case更为强大,match-case是一种结构匹配模式,与switch-case也有许多的差异,所以单列一章进行学习。

简单用法

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 都无法匹配时,匹配这条,保证永远会匹配成功。

标量

标量是指case后面的匹配值是标量。

标量的用法与C、Java的用法基本相同。

注意,这里的标量只能是常量,以及与常量相当的枚举值,变量是不能作为case后面的匹配值使用的,变量在match-case中有特殊的作用,这一点与其他语言的switch是有很大的差异。

error_code = 500

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        #case error_code:   #这个是错误的,不允许使用任何变量
        #    return "HTTP-Internal Server Error!"
        case _:
            return "Something's wrong with the internet"

mystatus=400
print(http_error(400))

def capture(greeting):
    match greeting:
        case '':
            print("greeting is null!")
        case 'Jack':
            print('Hello Jack!')
        # case name:  #会提示 SyntaxError: name capture 'name' makes remaining patterns unreachable
        #     print(f'Hi {name}!')
        case _:
            print('other!')

capture('Jack')
capture('John')
capture('')

'''
Hello Jack!
other!
greeting is null!
'''

多值 

一个 case 也可以设置多个匹配条件,条件使用 | 隔开,例如:

...
    case 401|403|404:
        return "Not allowed"

注意:与C和Java不一样,多值不是使用逗号分割,而是使用 | 隔开,逗号在match-case中另有用处。

match-case只有OR模式,没有AND模式

枚举

可以通过定义枚举值来进行条件匹配,match-case看上去是把枚举值当做标量来处理。

class Color():
    RED = 1
    GREEN = 2
    BLUE = 3

class NewColor:
    YELLOW = 4

class Black():
    BLACK =5

def constant_value(color):
    match color:
        case Color.RED:
            print('RED')
        case NewColor.YELLOW:
            print('YELLOW')
        case other:
            print(f'{other=}')


constant_value(Color.RED)
constant_value(Color.GREEN)
constant_value(NewColor.YELLOW)
constant_value(4)

'''
RED
other=2
YELLOW
YELLOW
'''

条件

case后面可以是一个条件表达式,如:

score = 81
match score:
    case 100:
        print('满分!')
    case score if score >= 80:
        print(f'高分啊~ {score}')
    case score if score >= 60:
        print('及格万岁!')
    case _:
        print('不知道说什么。')

# 高分啊~ 81

高级用法

元组匹配

元组匹配时,可以匹配整个元组常量,也可以匹配元组的一部分常量,另一部使用变量代替。

代替的变量部分会被match-case赋值,是一种基于位置的绑定变量,这是match-case所特有的特性,对于不想取值的变量,可以使用"_"进行替代,对于多个可以使用"*"作为通配符进行替代,如下例子:

def printPoint(point):
    match point:
        case (0, 0):
            print("坐标原点")
        case (0, y):        #绑定变量y,第一个元素为0就匹配,并且只有2个元素
            print(f"Y={y}")
        case (0, 0, z):     #绑定变量z,第一、二个元素都是0,并且要三个元素的元组
            print(f"Z={z}")
        case (x, 0) if x > 30:
            print(f"X={x} and x > 30")
        case (x, 0):        #绑定变量x,第二个元素为0就匹配
            print(f"X={x}")
        case (a, 10):   #绑定变量是a,变量名任意都可以
            print(f"A2={a}")
        c
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值