閱讀180 返回首頁    go 技術社區[雲棲]


python中switch語句用法

python中是沒用switch語句的,這應該是體現python大道至簡的思想,python中一般多用字典來代替switch來實現。

#coding: utf-8
from __future__ import division

def jia(x,y):
    print x+y

def jian(x,y):
    print x-y

def cheng(x,y):
    print x*y

def chu(x,y):
    print x/y

operator = {'+':jia,'-':jian,'*':cheng,'/':chu}

def f(x,o,y):
    operator.get(o)(x,y)

f(3,'+',2)

上麵的代碼就用字典實現了選擇功能,要是在C++中實現上述功能,是用switch實現的,但是用python的字典實現起來更簡單

最後更新:2017-04-03 16:48:56

  上一篇:go Linux下安裝jdk報Permission denied以及chmod詳解
  下一篇:go python網絡爬蟲抓取圖片