分享

Python中switch-case实现

 MikeDoc 2011-11-18

Python不像C/C++,Java等有switch-case的语法。不过其这个功能,比如用Dictionary以及lambda匿名函数特性来替代实现。

比如PHP中的如下代码:

1
2
3
4
5
6
7
8
9
10
11
switch ($value) {
    case 'a':
        $result = $x * 5;
        break;
    case 'b':
        $result = $x + 7;
        break;
    case 'c':
        $result = $x - 2;
        break;
}

Python的等价实现为:

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

如果是稍微复杂一点的函数,也可以做到,比如我们计算加减乘除,函数定义如下:

1
2
3
4
5
6
7
8
def add(a,b):
    return a + b
def multi(a,b):
    return a* b
def sub(a,b):
    return a - b
def div(a,b):
    return a/ b#b is non-zero

如果是switch实现的话,case(‘操作数’)来判断之行的对应函数。看看Python的实现:

1
2
3
4
5
6
7
8
9
10
11
def calc(type,x,y):
    calculation  = {'+':lambda:add(x,y),
                     '*':lambda:multi(x,y),
                     '-':lambda:sub(x,y),
                     '/':lambda:div(x,y)}
    return calculation[type]()
#calc = {1:lambda:add(x,y)}[value]()
 
result1 = calc('+',3,6)
result2 = calc('-',3,6)
print result1, result2

这里用的结构如下:

1
2
3
4
message = { 'type1': lambda: func1(some_data),
            'type2': lambda: func2(other_data),
          }
return message[type]()

还有更加复杂的就是自定义一个Switch类了,可以参考http://code./recipes/410692-readable-switch-construction-without-lambdas-or-di/

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多