浙江省高等学校教师教育理论培训

微信搜索“毛凌志岗前心得”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

http://simonwillison.net/2004/May/7/switch/

Switch statements in Python

Python doesn’t support a native switch statement. I’ve found myself using the following coding idiom instead recently which seems to work pretty well:

{'option1': function1,
 'option2': function2,
 'option3': function3,
 'option4': function4}[value]()

This works with lambdas as well, for inline calculations. Here’s a switch statement that assigns to a variable in PHP:

switch ($value) {
    case 'a':
        $result = $x * 5;
        break;
    case 'b':
        $result = $x + 7;
        break;
    case 'c':
        $result = $x - 2;
        break;
}

And here’s the equivalent code in Python:

result = {
  'a': lambda x: x * 5,
  'b': lambda x: x + 7,
  'c': lambda x: x - 2
}[value](x)
posted on 2012-02-16 22:29  lexus  阅读(202)  评论(0编辑  收藏  举报