標籤:switch python lambda
在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 sdef 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 reclass 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.StopExecutionclass 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