Python的switch…case语法

Python没有switch…case的语法,不过可以用Dictionary和lambda匿名函数的特性来写出同样优雅的代码,比如这段javascript代码:

switch(value){
    case 1:
        func1();
        break;
    case 2:
        func2();
        break;
    case 3:
        func3();
        break;
}

等价的Python代码:

{
  1: lambda: func1,
  2: lambda: func2,
  3: lambda: func3
}[value]()

带赋值的情况:

result = {
  'a': lambda x: x * 5,
  'b': lambda x: x + 7,
  'c': lambda x: x - 2
}[value](x)

用try…catch来实现带Default的情况,不过这个形式就感觉差些了:

try:
    {'option1': func1,
     'option2': func2,
     'option3': func3}[value]()
except KeyError:
    # default action

附上google到的相关内容(评论中的讨论也值得一看):

2 Responses

Leave a Comment

(Necessary)

(Necessary, will not be published)

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.