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
輸出:
補(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)行效果如下所示:
![](/d/20211017/b5042e8f78efd929f020903b1d7bdf07.gif)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- python switch 實(shí)現(xiàn)多分支選擇功能
- Python通過(guò)字典映射函數(shù)實(shí)現(xiàn)switch
- Python為何不支持switch語(yǔ)句原理詳解
- Python基于字典實(shí)現(xiàn)switch case函數(shù)調(diào)用
- Python Switch Case三種實(shí)現(xiàn)方法代碼實(shí)例
- 使用 Python 實(shí)現(xiàn)簡(jiǎn)單的 switch/case 語(yǔ)句的方法
- Python分支結(jié)構(gòu)(switch)操作簡(jiǎn)介
- Python中實(shí)現(xiàn)switch功能實(shí)例解析
- python中Switch/Case實(shí)現(xiàn)的示例代碼
- 淺談python為什么不需要三目運(yùn)算符和switch