python 中switch的实现

来源:互联网 发布:湛洪果 知乎 编辑:程序博客网 时间:2024/06/13 01:21

转载自:http://blog.chinaunix.net/uid-1706385-id-2834875.html

There is currently no switch statement in Python. Often this is not a problem and can be handled through a series of if-elif-else statements. However, there are many other ways to handle the deficiency. The following example shows how to create a simple switch statement in Python:


def a(s):
    print s
def switch(ch):
    try:
      {'1': lambda : a("one"),
       '2': lambda : a("two"),
      '3': lambda : a("three"),
       'a': lambda : a("Letter a")
      }[ch]()
    except KeyError:
      a("Key not Found")


eg:

>>switch('1')
one
>>switch('a')
Letter a
>>switch('b')
Key not Found

0 0