PythonStudy——Python 中Switch-Case 结构的实现

 学习Python过程中,发现Python没有Switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现。所以不妨自己来实现Switch-Case功能。

方法一

通过字典实现

def foo(var):
    return {
        'a': '1',
        'b': '2',
        'c': '3'
    }.get(var, 'error')   # 'error'为默认返回值,可自设置

print(foo('a'))
print(foo('b'))
print(foo('c'))

Output:
1
2
3

方法二

通过匿名函数实现

def foo(var,x):
    return {
            'a': lambda x: x+1,
            'b': lambda x: x+2,
            'c': lambda x: x+3, 
    }[var](x)

 

posted @ 2019-04-17 08:48  挺锅锅  阅读(540)  评论(0编辑  收藏  举报