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 语法的支持,可以有其他的实现方式(但是逐个匹配的效率较差) -> 查看文章

 

相关文章:

  • 2021-07-01
  • 2021-07-11
  • 2021-06-29
  • 2021-12-27
  • 2022-12-23
  • 2021-11-18
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-30
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
  • 2021-04-04
  • 2022-12-23
相关资源
相似解决方案