Python中switch-case实现

Python中switch-case实现


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 = { 'type 1 ' : lambda : func 1 ( some_data ) ,
             'type 2 ' : lambda : func 2 ( other_data ) ,
           }
return message [type] ( )

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值