Python switch(多分支选择)的实现

Python 中没有 switch/case 语法,如果使用 if/elif/else 会出现代码过长、不清晰等问题。

而借助字典就可以实现 switch 的功能

示例:

def case1():                            # 第一种情况执行的函数
    print('This is the case1')


def case2():                            # 第二种情况执行的函数
    print('This is the case2')


def case3():                            # 第三种情况执行的函数
    print('This is the case3')

def default(): # 默认情况下执行的函数 print('No such case')
switch
= {'case1': case1, # 注意此处不要加括号 'case2': case2, 'case3': case3, } choice = 'case1' # 获取选择 switch.get(choice, default)() # 执行对应的函数,如果没有就执行默认的函数

switch.get(choice, default)() 先去字典中查找 key 之后执行以 key 对应的 value 为函数名的函数,如果没有找到相应的 key 就执行默认函数。

 

 


 

Python3.10 中新增了对 match case 语法的支持,可以有其他的实现方式(但是逐个匹配的效率较差) -> 查看文章

 

posted on 2019-03-26 16:48  doubtful  阅读(110129)  评论(0编辑  收藏  举报

导航