Python中的Switch語句實現
switch語句
switch語句用於編寫多分支結構的程序,類似與if…elif…else語句
switch語句表達的分之結構比if…elif…else語句表達的更清晰,代碼的可讀性更高
Python中沒有switch語句關鍵字,但可以通過字典dict實現switch語句的功能,實現方法分爲兩步:首先,定義一個字典;其次,調用字典的get()獲取相應的表達式
switch有什麼好處?
函數調用,通過字典調用函數{1:case1,2:case2}.get(x,lambda *arg,**key:)()
case-通過if語句進行±*/運算
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
def operator(x,o,y):
if o=='+':
jia(x,y)
elif o=='-':
jian(x,y)
elif o=='*':
cheng(x,y)
elif o=='/':
chu(x,y)
else:
pass
print(operator(2,'+',4))
這樣寫函數,當執行除法操作時,前3次判斷都是多餘的,效率較低,if...elif...else
語句天生會有優先級的區分
用dict類型改寫switch語句如下;
operator={'+':jia,'-':jian,'*':cheng,'/':chu}
print(operator['+'])
<function jia at 0x00000000030F6400>
>>> operator['+'](2,3)
5
>>> print(operator['+'](2,3))
5
>>>
根據dict字典類型數據的特性,如果沒有對應[key],會報錯,那我們可以改用dict.get()方法替換替換對key-value的獲取,即switch判斷。
>>> print(operator.get('*')(5,3))
15
>>>
>>> def f(x,o,y):
print(operator.get(o)(x,y))
>>> f(3,'*',9)
27