python switch 實現(xiàn)多分支選擇功能
相信玩過幾天 python 的小伙伴都知道,python 里并沒有 switch 關(guān)鍵字實現(xiàn),那這是為什么呢?
根據(jù)官方說法 PEP 3103 - A Switch/Case Statement.
實現(xiàn) switch case 需要被判斷的變量是可哈希和可比較的,這與 python 提倡的靈活性有沖突。在實現(xiàn)上優(yōu)化不好做,可能到最后最差的情況匯編出來和 if else 組是一樣的,所以 python 沒有支持
但是沒有 switch 關(guān)鍵字,不代表不能實現(xiàn)類似效果,接下來通過幾個小程序來說明此類問題
if else 判斷我們通過最常用的 if else 判斷來實現(xiàn)一段代碼
def matching_if(type): if type == 0: return ’優(yōu)惠1塊錢’ elif type == 1: return ’優(yōu)惠10塊錢’ elif type == 2: return ’優(yōu)惠100塊錢’ return ’無優(yōu)惠’if __name__ == ’__main__’: print(matching_if(1)) print(matching_if(999))
執(zhí)行結(jié)果如下:
’’’打印輸出: 優(yōu)惠10塊錢 無優(yōu)惠’’’
dict 字典可以使用字典實現(xiàn) switch case,這種方式易維護,同時也能夠減少代碼量。如下是使用字典模擬的 switch case 實現(xiàn):
def matching_dict(type): types = { 0: ’優(yōu)惠1塊錢’, 1: ’優(yōu)惠10塊錢’, 2: ’優(yōu)惠100塊錢’ } return types.get(type, ’無優(yōu)惠’)if __name__ == ’__main__’: print(matching_dict(1)) print(matching_dict(999))
代碼從整體上看著簡潔了很多,那還有沒有別的方式呢?
函數(shù)判斷函數(shù)判斷從代碼數(shù)量來說并無優(yōu)勢,優(yōu)勢點在于其靈活性,如果根據(jù)不同的類型作出大量操作,函數(shù)運算無疑是最優(yōu)的方式
def one(): return ’優(yōu)惠1塊錢’def two(): return ’優(yōu)惠10塊錢’def three(): return ’優(yōu)惠100塊錢’def default(): return ’無優(yōu)惠’def matching_method(type): types = { 0: one, 1: two, 2: three } method = types.get(type, default) return method()if __name__ == ’__main__’: print(matching_method(1)) print(matching_method(999))
優(yōu)雅的代碼是程序員的追求之一,作者本人也有一定程度的代碼潔癖,所以涉及此類應(yīng)用,會選擇第二種 dict 字典類型應(yīng)用
lambda 函數(shù)這里推出一款 lambda 配合 dict 字典的方式,可以對運算條件作出更為精準的計算
def matching_lambda(type): matching_dict = lambda x: { x == 0: ’優(yōu)惠1塊錢’, x == 1: ’優(yōu)惠10塊錢’, x == 2: ’優(yōu)惠100塊錢’ } return matching_dict(type)[True]if __name__ == ’__main__’: print(matching_lambda(1)) print(matching_lambda(2))結(jié)言
由于作者水平有限, 歡迎大家能夠反饋指正文章中錯誤不正確的地方, 感謝 🙏
到此這篇關(guān)于python switch 實現(xiàn)多分支選擇功能的文章就介紹到這了,更多相關(guān)python switch 多分支實現(xiàn)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
