在Python中替换switch语句?

我想用Python编写一个函数,该函数根据输入索引的值返回不一样的固定值。 html

在其余语言中,我将使用switchcase语句,可是Python彷佛没有switch语句。 在这种状况下,推荐的Python解决方案是什么? python


#1楼

若是您有一个复杂的case块,能够考虑使用函数字典查找表... 函数

若是您还没有执行此操做,那么最好进入调试器并准确查看字典如何查找每一个函数。 spa

注意: 不要使用“()”的状况下/字典查找内部或它会调用每一个函数被建立字典/ case块。 请记住这一点,由于您只想使用哈希样式查找一次调用每一个函数。 调试

def first_case():
    print "first"

def second_case():
    print "second"

def third_case():
    print "third"

mycase = {
'first': first_case, #do not use ()
'second': second_case, #do not use ()
'third': third_case #do not use ()
}
myfunc = mycase['first']
myfunc()

#2楼

扩展“ dict as switch”的想法。 若是要为开关使用默认值: code

def f(x):
    try:
        return {
            'a': 1,
            'b': 2,
        }[x]
    except KeyError:
        return 'default'

#3楼

若是您想要默认值,则可使用字典get(key[, default])方法: htm

def f(x):
    return {
        'a': 1,
        'b': 2
    }.get(x, 9)    # 9 is default if x not found

#4楼

def f(x):
     return 1 if x == 'a' else\
            2 if x in 'bcd' else\
            0 #default

简短易读,具备默认值,并支持条件和返回值中的表达式。 索引

可是,它比使用字典的解决方案效率低。 例如,Python必须先扫描全部条件,而后再返回默认值。 get


#5楼

定义: it

def switch1(value, options):
  if value in options:
    options[value]()

容许您使用至关简单的语法,将案例捆绑到地图中:

def sample1(x):
  local = 'betty'
  switch1(x, {
    'a': lambda: print("hello"),
    'b': lambda: (
      print("goodbye," + local),
      print("!")),
    })

我一直试图以一种让我摆脱“ lambda:”的方式从新定义开关,可是放弃了。 调整定义:

def switch(value, *maps):
  options = {}
  for m in maps:
    options.update(m)
  if value in options:
    options[value]()
  elif None in options:
    options[None]()

容许我将多个案例映射到同一代码,并提供默认选项:

def sample(x):
  switch(x, {
    _: lambda: print("other") 
    for _ in 'cdef'
    }, {
    'a': lambda: print("hello"),
    'b': lambda: (
      print("goodbye,"),
      print("!")),
    None: lambda: print("I dunno")
    })

每一个重复的案例都必须放在本身的字典中; 在查找值以前,switch()合并字典。 它仍然比我想要的还要难看,可是它具备在表达式上使用哈希查找的基本效率,而不是循环遍历全部键。

相关文章
相关标签/搜索