Python 使用dict實(shí)現(xiàn)switch的操作
Python3還是沒(méi)有switch,可以利用if-else來(lái)實(shí)現(xiàn),但是非常不方便。使用dict來(lái)實(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ù)說(shuō)有個(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語(yǔ)句相信大家都很熟悉,而且swith語(yǔ)句表達(dá)的分支結(jié)構(gòu)比if...elif...else語(yǔ)句表達(dá)更清晰,代碼的可讀性更高,但是在Python中,卻沒(méi)有提供這一個(gè)關(guān)鍵字。那我們?cè)撊绾瓮ㄟ^(guò)其他方式來(lái)實(shí)現(xiàn)這類似的結(jié)構(gòu)呢?
雖然沒(méi)有switch語(yǔ)句,但是我們可以通過(guò)Python中的dict即字典來(lái)實(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. XML在語(yǔ)音合成中的應(yīng)用2. 不要在HTML中濫用div3. jscript與vbscript 操作XML元素屬性的代碼4. XML入門的常見(jiàn)問(wèn)題(三)5. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)6. .NET Framework各版本(.NET2.0 3.0 3.5 4.0)區(qū)別7. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)8. 基于PHP做個(gè)圖片防盜鏈9. ASP基礎(chǔ)入門第四篇(腳本變量、函數(shù)、過(guò)程和條件語(yǔ)句)10. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)
