在linux的shell中我们习惯使用case语句来做分支处理,然而Python中却省略了这个函数,经过多方查找,发现其实case语句在C语言中是通过查对应的hash表,来进行跳转的。在Python中我们可以通过三种方法来实现这种功能。1、字典;2、lambda;3、switch类。
1、字典
dictCase={‘case1‘:func1,‘case2‘:func2....‘caseN‘:funcN}
#注意字典中对应的是函数名,不要圆括号。
在调用的时候使用字典的get函数来实现default选项:
dictCase.get(caseN,default_Func)()
2、匿名函数lambda
网上常见的例子:
result = {
‘a‘: lambda x: x * 5,
‘b‘: lambda x: x + 7,
‘c‘: lambda x: x - 2
}[value](x)
看不太懂。。。
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
这个例子不错,但总觉的这样不太好看,没字典灵活。
我自己的例子:
1 #!/usr/bin/env python 2 import sys 3 4 def f1(a): 5 print a 6 7 def b(b): 8 print b+1 9 10 g=lambda x:x 11 12 #m=sys.argv[1] 13 #n=sys.argv[2] 14 #print m,n 15 m=input("functionname:") 16 n=input("number:") 17 try: 18 g(m)(n) 19 except: 20 print "function not exists:{f1,b}" 21#使用try来实现default函数
3、安装switch类:https://pypi.python.org/pypi/switch/1.1.0#downloads
有了前面两种,安装这个类就有点无聊了。。。
# -*- coding: utf-8 -*- from __future__ import with_statement __version__ = ‘1.1.0‘ __all__ = [‘CSwitch‘, ‘Switch‘] import re class Switch(object): class StopExecution(Exception): pass def __init__(self, switch_value, fall_through=False): self._switch_value = switch_value self._default_fall_through = fall_through self._fall_through = False self._matched_case = False self._default_used = False def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): return exc_type is self.StopExecution def __call__(self, case_value, *case_values, **kwargs): return self.call( lambda switch_value: any(switch_value == v for v in (case_value, ) + case_values), **kwargs ) def match(self, match_value, *match_values, **kwargs): def test(switch_value): # It is safe to call `re.compile()` on a compiled pattern: # a=re.compile(‘test‘); assert a is re.compile(a) str_switch_value = str(switch_value) re_tests = (re.compile(v) for v in (match_value, ) + match_values) return any(regex.match(str_switch_value) for regex in re_tests) return self.call(test, **kwargs) def call(self, test, fall_through=None): if self._default_used: raise SyntaxError(‘Case after default is prohibited‘) self._check_finished() if self._fall_through or test(self._switch_value): self._matched_case = True self._fall_through = fall_through if fall_through is not None else self._default_fall_through return True return False @property def default(self): self._check_finished() self._default_used = True return not self._matched_case def _check_finished(self): if self._matched_case is True and self._fall_through is False: raise self.StopExecution class CSwitch(Switch): """ CSwitch is a shortcut to call Switch(test_value, fall_through=True) """ def __init__(self, switch_value): super(CSwitch, self).__init__(switch_value, fall_through=True)
本文出自 “hiubuntu” 博客,请务必保留此出处http://qujunorz.blog.51cto.com/6378776/1538985
Python笔记:替代case语句的字典和匿名函数(lambda),布布扣,bubuko.com
Python笔记:替代case语句的字典和匿名函数(lambda)
原文地址:http://qujunorz.blog.51cto.com/6378776/1538985