others - 在python中,switch语句的替换品?

我想在python中编写一个函数,根据输入的值,该函数返回不同的固定值。

在其它语言中,我可以使用switch或case语句,Python 似乎没有switch语句,在这种情况下,推荐的Python解决方案是什么?

时间:

你可以用字典:


def f(x):


 return {


 \'a\': 1,


 \'b\': 2,


 }[x]



如果你想要默认值,可以使用字典get(key[, default])方法:


def f(x):


 return {


 \'a\': 1,


 \'b\': 2


 }.get(x, 9) # 9 is default if x not found



我一直喜欢这样做


result = {


 \'a\': lambda x: x * 5,


 \'b\': lambda x: x + 7,


 \'c\': lambda x: x - 2


}[value](x)



来自这里

除了字典方法(我非常喜欢)之外,你还可以使用if-elif-else来获得switch/case/default功能:


if x == \'a\':


 # Do the thing


elif x == \'b\':


 # Do the other thing


if x in \'bc\':


 # Fall-through by not using elif, but now the default case includes case \'a\'!


elif x in \'xyz\':


 # Do yet another thing


else:


 # Do the default



我最喜欢的switch/case的python配方是:


choices = {\'a\': 1, \'b\': 2}


result = choices.get(key, \'default\')



和11行C代码比较:


// C Language version of a simple \'switch/case\'.


switch( key ) 


{


 case \'a\' :


 result = 1;


 break;


 case \'b\' :


 result = 2;


 break;


 default :


 result = -1;


}



你甚至可以通过使用元组来分配多个变量:


choices = {\'a\': (1, 2, 3), \'b\': (4, 5, 6)}


(result1, result2, result3) = choices.get(key, (\'default1\', \'default2\', \'default3\'))




class switch(object):


 value = None


 def __new__(class_, value):


 class_.value = value


 return True



def case(*args):


 return any((arg == switch.value for arg in args))



使用方法:


while switch(n):


 if case(0):


 print"You typed zero."


 break


 if case(1, 4, 9):


 print"n is a perfect square."


 break


 if case(2):


 print"n is an even number."


 if case(2, 3, 5, 7):


 print"n is a prime number."


 break


 if case(6, 8):


 print"n is an even number."


 break


 print"Only single-digit numbers are allowed."


 break



测试:


n = 2


#Result:


#n is an even number.


#n is a prime number.


n = 11


#Result:


#Only single-digit numbers are allowed.



我最喜欢的是recipes ,你将非常喜欢它,它是我觉得和switch case语句最接近的一个,特别是在特性中。


class switch(object):


 def __init__(self, value):


 self.value = value


 self.fall = False



 def __iter__(self):


"""Return the match method once, then stop"""


 yield self.match


 raise StopIteration



 def match(self, *args):


"""Indicate whether or not to enter a case suite"""


 if self.fall or not args:


 return True


 elif self.value in args: # changed for v1.5, see below


 self.fall = True


 return True


 else:


 return False



这是一个例子:


# The following example is pretty much the exact use-case of a dictionary,


# but is included for its simplicity. Note that you can include statements


# in each suite.


v = \'ten\'


for case in switch(v):


 if case(\'one\'):


 print 1


 break


 if case(\'two\'):


 print 2


 break


 if case(\'ten\'):


 print 10


 break


 if case(\'eleven\'):


 print 11


 break


 if case(): # default, could also just omit condition or \'if True\'


 print"something else!"


 # No need to break here, it\'ll stop anyway



# break is used here to look as much like the real thing as possible, but


# elif is generally just as good and more concise.



# Empty suites are considered syntax errors, so intentional fall-throughs


# should contain \'pass\'


c = \'z\'


for case in switch(c):


 if case(\'a\'): pass # only necessary if the rest of the suite is empty


 if case(\'b\'): pass


 # ...


 if case(\'y\'): pass


 if case(\'z\'):


 print"c is lowercase!"


 break


 if case(\'A\'): pass


 # ...


 if case(\'Z\'):


 print"c is uppercase!"


 break


 if case(): # default


 print"I dunno what c was!"



# As suggested by Pierre Quentel, you can even expand upon the


# functionality of the classic \'case\' statement by matching multiple


# cases in a single shot. This greatly benefits operations such as the


# uppercase/lowercase example above:


import string


c = \'A\'


for case in switch(c):


 if case(*string.lowercase): # note the * for unpacking as arguments


 print"c is lowercase!"


 break


 if case(*string.uppercase):


 print"c is uppercase!"


 break


 if case(\'!\', \'?\', \'.\'): # normal argument passing style also applies


 print"c is a sentence terminator!"


 break


 if case(): # default


 print"I dunno what c was!"




class Switch:


 def __init__(self, value):


 self.value = value



 def __enter__(self):


 return self



 def __exit__(self, type, value, traceback):


 return False # Allows a traceback to occur



 def __call__(self, *values):


 return self.value in values



from datetime import datetime



with Switch(datetime.today().weekday()) as case:


 if case(0):


 # Basic usage of switch


 print("I hate mondays so much.")


 # Note there is no break needed here


 elif case(1,2):


 # This switch also supports multiple conditions (in one line)


 print("When is the weekend going to be here?")


 elif case(3,4):


 print("The weekend is near.")


 else:


 # Default would occur here


 print("Let\'s go have fun!") # Didn\'t use case for example purposes



...