Python switch语句的巧妙实现
在其他一些语言里,如Java,C等,它们提供了switch语句来根据提供的值返回不同的结果。而在python里是没有类似的语句。
基本实现
使用Python的字典可以很简单实现switch语句的功能。
def f(x):
    return {
        'a': 1,
        'b': 2,
    }[x]
switch的default值
结合get()返回默认值:
def f(x):
    return {
        'a': 1,
        'b': 2
    }.get(x, 10)
如果没找到,返回默认值10。
使用函数计算返回值
可以定义函数来计算返回值:
result = {
  'a': lambda x: x * 5,
  'b': lambda x: x + 7,
  'c': lambda x: x - 2
}[value](x)