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. React+umi+typeScript創(chuàng)建項(xiàng)目的過程2. ASP中常用的22個(gè)FSO文件操作函數(shù)整理3. ASP編碼必備的8條原則4. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp5. 三個(gè)不常見的 HTML5 實(shí)用新特性簡(jiǎn)介6. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯(cuò)問題分析7. SharePoint Server 2019新特性介紹8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析10. php測(cè)試程序運(yùn)行速度和頁面執(zhí)行速度的代碼
