1. 程式人生 > >Python中Swithch Case語法實現

Python中Swithch Case語法實現

some case 其他 -s clas rec tro imp recipe

摘自網絡

python本身沒有switch語句,解決方法有以下3種:

A.使用dictionary
values = {
value1: do_some_stuff1,
value2: do_some_stuff2,
...
valueN: do_some_stuffN,
}
values.get(var, do_default_stuff)()
網上另一個例子比較容易看懂:
#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)

B.使用lambda
result = {
‘a‘: lambda x: x * 5,
‘b‘: lambda x: x + 7,
‘c‘: lambda x: x - 2
}[value](x)


C.Brian Beck提供了一個類 switch 來實現其他語言中switch的功能
略……

Python中Swithch Case語法實現