首页 > 代码库 > Python中Swithch Case语法实现

Python中Swithch Case语法实现

摘自网络

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语法实现