现在的位置: 首页 > 综合 > 正文

Python中Swithch Case语法实现

2013年10月08日 ⁄ 综合 ⁄ 共 1699字 ⁄ 字号 评论关闭

其他语言中,switch语句大概是这样的

  1. switch (var)
  2. {
  3.     case value1: do_some_stuff1();
  4.     case value2: do_some_stuff2();
  5.     ...
  6.     case valueN: do_some_stuffN();
  7.     default: do_default_stuff();
  8. }
而python本身没有switch语句,解决方法有以下3种:
A.使用dictionary
values = {
value1: do_some_stuff1,
value2: do_some_stuff2,
...
valueN: do_some_stuffN,
}
values.get(var, do_default_stuff)()

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的功能
  1. # This class provides the functionality we want. You only need to look at
  2. # this if you want to know how this works. It only needs to be defined
  3. # once, no need to muck around with its internals.
  4. class switch(object):
  5.     def __init__(self, value):
  6.         self.value = value
  7.         self.fall = False
  8.     def __iter__(self):
  9.         """Return the match method once, then stop"""
  10.         yield self.match
  11.         raise StopIteration
  12.     def match(self, *args):
  13.         """Indicate whether or not to enter a case suite"""
  14.         if self.fall or not args:
  15.             return True
  16.         elif self.value in args: # changed for v1.5, see below
  17.             self.fall = True
  18.             return True
  19.         else:
  20.             return False
  21. # The following example is pretty much the exact use-case of a dictionary,
  22. # but is included for its simplicity. Note that you can include statements
  23. # in each suite.
  24. v = 'ten'
  25. for case in switch(v):
  26.     if case('one'):
  27.         print 1
  28.         break
  29.     if case('two'):
  30.         print 2
  31.         break
  32.     if case('ten'):
  33.         print 10
  34.         break
  35.     if case('eleven'):
  36.         print 11
  37.         break
  38.     if case(): # default, could also just omit condition or 'if True'
  39.         print "something else!"
  40.         # No need to break here, it'll stop anyway

抱歉!评论已关闭.