Python 使用dict實(shí)現(xiàn)switch的操作
Python3還是沒有switch,可以利用if-else來實(shí)現(xiàn),但是非常不方便。使用dict來實(shí)現(xiàn)會(huì)比較簡(jiǎn)潔優(yōu)雅。
# -*- coding: utf-8 -*-'''Python利用dict實(shí)現(xiàn)switch''' def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): assert(y != 0)return x / y mapping = {'+': add, '-': subtract, '*': multiply, '/': divide} def cal(x, y, symbol='+'): assert(symbol in mapping) return mapping.get(symbol)(x, y) if __name__ == '__main__': result = cal(3, 0, '&')
補(bǔ)充:python 字典dict實(shí)現(xiàn)switch case【實(shí)際應(yīng)用】(非dict.get()方法實(shí)現(xiàn))
看了不少帖子,幾乎都是采用字典的.get()方法實(shí)現(xiàn),據(jù)說有個(gè)弊端:“會(huì)將字典每個(gè)帶括號(hào)的方法都執(zhí)行一遍”。
以下方法可避免該弊端,并可以傳參。如有不足請(qǐng)指正!
#!/usr/bin/python3 # conf_cmd = conf_items['cmd'].split(':')[0] test_no = 'T1'#test_no = 'T2'#test_no = 'T3' id = 1 def test1(id): print('test1:%d' % id) def test2(id): print('test2') def test3(id): print('test3') funcs = {'T1': test1, 'T2': test2, 'T3': test3} try: func = funcs[test_no] func(id)except Exception: pass
輸出:
test1:1
補(bǔ)充:Python實(shí)現(xiàn)類似switch的分支結(jié)構(gòu)
switch語句相信大家都很熟悉,而且swith語句表達(dá)的分支結(jié)構(gòu)比if...elif...else語句表達(dá)更清晰,代碼的可讀性更高,但是在Python中,卻沒有提供這一個(gè)關(guān)鍵字。那我們?cè)撊绾瓮ㄟ^其他方式來實(shí)現(xiàn)這類似的結(jié)構(gòu)呢?
雖然沒有switch語句,但是我們可以通過Python中的dict即字典來實(shí)現(xiàn)類似switch結(jié)構(gòu)的方法
實(shí)現(xiàn)代碼如下:
def operator(o,x,y): result={ ’+’ : x+y, ’-’ : x-y, ’*’ : x*y, ’/’ : x/y } print(result.get(o))oper=input()//接收從鍵盤輸入的數(shù)據(jù)operator(oper,4,2)
運(yùn)行效果如下所示:
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. ASP常用日期格式化函數(shù) FormatDate()2. 如何在jsp界面中插入圖片3. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))4. 得到XML文檔大小的方法5. XML入門的常見問題(二)6. ASP.NET Core實(shí)現(xiàn)中間件的幾種方式7. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法8. JavaScrip簡(jiǎn)單數(shù)據(jù)類型隱式轉(zhuǎn)換的實(shí)現(xiàn)9. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法10. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)
