Python3還是沒有switch,可以利用if-else來實現,但是非常不方便。使用dict來實現會比較簡潔優雅。
# -*- coding: utf-8 -*-
"""
Python利用dict實現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, "")
補充:python 字典dict實現switch case【實際應用】(非dict.get()方法實現)
看了不少帖子,幾乎都是采用字典的.get()方法實現,據說有個弊端:“會將字典每個帶括號的方法都執行一遍”。
以下方法可避免該弊端,并可以傳參。如有不足請指正!
#!/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
輸出:
補充:Python實現類似switch的分支結構
switch語句相信大家都很熟悉,而且swith語句表達的分支結構比if...elif...else語句表達更清晰,代碼的可讀性更高,但是在Python中,卻沒有提供這一個關鍵字。那我們該如何通過其他方式來實現這類似的結構呢?
雖然沒有switch語句,但是我們可以通過Python中的dict即字典來實現類似switch結構的方法
實現代碼如下:
def operator(o,x,y):
result={
'+' : x+y,
'-' : x-y,
'*' : x*y,
'/' : x/y
}
print(result.get(o))
oper=input()//接收從鍵盤輸入的數據
operator(oper,4,2)
運行效果如下所示:

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- python switch 實現多分支選擇功能
- Python通過字典映射函數實現switch
- Python為何不支持switch語句原理詳解
- Python基于字典實現switch case函數調用
- Python Switch Case三種實現方法代碼實例
- 使用 Python 實現簡單的 switch/case 語句的方法
- Python分支結構(switch)操作簡介
- Python中實現switch功能實例解析
- python中Switch/Case實現的示例代碼
- 淺談python為什么不需要三目運算符和switch