python之 利用字典与函数实现switch case功能

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


字典+函数实现switch模式下的四则运算:(switch 下运算符只用判断一次,不同于 if 、elsif 判断)

法1:
-- 代码
[root@bigdata01 ~]# cat t1.py
#!/usr/bin/python
#coding:utf-8

def add(x,y):
return x+y

def sub(x,y):
return x-y

def mul(x,y):
return x*y

def div(x,y):
return x/y

operator = {"+":add,"-":sub,"*":mul,"/":div}

def f(x,o,y):
print operator.get(o)(x,y)

f(2,"+",2)
f(2,"-",2)
f(2,"*",2)
f(2,"/",2)


-- 运行情况
[root@bigdata01 ~]# python t1.py
4
0
4
1

 

法2:
-- 代码
[root@bigdata01 ~]# cat t2.py
def calc(type,x,y):
calculation = {'+':lambda :x+y,
'*':lambda:x-y,
'-':lambda:x*y,
'/':lambda:x/y}
return calculation[type]()

result1 = calc('+',3,6)
result2 = calc('-',3,6)
result3 = calc('*',3,6)
result4 = calc('/',3,6)
print result1
print result2
print result3
print result4

-- 运行情况
[root@bigdata01 ~]# python t2.py
9
18
-3
0

总结: 利用 python 字典中的 key > 相当于 其他语言中的 switch,python 字典中 value 调用 对应函数 > 相当于 其他语言中的 case

posted on 2017-12-10 14:25  张冲andy  阅读(2393)  评论(0编辑  收藏  举报

导航