python switch..case 与 三目运算符
对于三目运算符(ternary operator),python可以用conditional expressions来替代
如对于x<5?1:0可以用下面的方式来实现
1if x<5else 0
注: conditional expressions是在python 2.5之前引入的,所以以上代码仅适用于2.5以及之后的版本
对于2.5之前的版本,可以用下面这种形式
X<5and1or 0
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/
浙公网安备 33010602011771号