高护木的规矩acfun:Python中switch-case实现

来源:百度文库 编辑:偶看新闻 时间:2024/04/29 06:00:20
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.activestate.com/recipes/410692-readable-switch-construction-without-lambdas-or-di/