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()//接收從鍵盤(pán)輸入的數(shù)據(jù)operator(oper,4,2)
運(yùn)行效果如下所示:
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. Python 的 __str__ 和 __repr__ 方法對(duì)比2. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法3. Spring security 自定義過(guò)濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)4. IntelliJ IDEA設(shè)置背景圖片的方法步驟5. docker /var/lib/docker/aufs/mnt 目錄清理方法6. Python TestSuite生成測(cè)試報(bào)告過(guò)程解析7. 學(xué)python最電腦配置有要求么8. JAMon(Java Application Monitor)備忘記9. Python Scrapy多頁(yè)數(shù)據(jù)爬取實(shí)現(xiàn)過(guò)程解析10. Python OpenCV去除字母后面的雜線操作
