通常情况下,我们常用字典函数实现Python的switch语句:
#coding:utf8
#add minus divide using python
from __future__ import division
def jia(x,y):
return x+y
def jian(x,y):
return x-y
def cheng(x,y):
return x*y
def chu(x,y):
return x/y
operator={"+":jia,"-":jian,"*":cheng,"/":chu}
def f(x,o,y):
print(operator.get(o)(x,y))
f(1,'+',3)
f(1,'-',3)
f(2,'*',3)
f(1,'/',3)
当然,还有一种更简洁的方法:
#coding:utf8
#add minus divide using python
from __future__ import division
x=1
y=2
operator='/'
result={
"+":x+y,
"-":x-y,
"*":x*y,
"/":x/y
}
print(result.get(operator))
如果你理解了上面的代码,那下面代码的意思也就不难理解了:
{1:case1,2:case2}.get(x,lambda *args,**key:)()