zoukankan      html  css  js  c++  java
  • 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 就执行默认函数。

  • 相关阅读:
    2016第13周四
    2016第13周周三
    2016第13周二
    2016第13周一
    2016第12周日
    2016第11周五
    2016第11周四
    前端的自我成长
    Java单例模式和volatile关键字
    大约 Apple Metal API 一些想法
  • 原文地址:https://www.cnblogs.com/dbf-/p/10601216.html
Copyright © 2011-2022 走看看