dru*_*rum 0 python switch-statement
可能重复:
python中switch语句的替换?
假设我有一个Python列表:
list =('ADD','SUB','PUSH','POP')
我想根据输入运行一个函数,该输入可以是列表中的任何值.
而不是为每个元素编写switch case语句list,是否有更紧凑的编写方式?
我的理由是这个名单在未来的增长情况.
嗯,还有就是在Python没有开关/ case语句.
对于小的list,你想使用if/ elif:
def do_stuff(x, *args):
if x == 'ADD':
return do_add(*args)
elif x == 'SUB':
return do_sub(*args)
# …
else:
raise RuntimeError('Never heard of {}'.format(x))
Run Code Online (Sandbox Code Playgroud)
对于更大的list,你想确保每个case都是一个函数(我已经假设上面,但如果你有代码return args[0] + args[1],你必须将它改成一个do_add函数),并dict为函数创建一个映射名称:
func_map = {'ADD': do_add, 'SUB': do_sub, … }
def do_stuff(x, *args):
try:
return func_map[x](*args)
except KeyError:
raise RuntimeError('Never heard of {}'.format(x))
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为在Python中,函数是普通对象,可以像任何其他对象一样传递.因此,您可以将它们存储在a中dict,从中检索它们dict,然后仍然可以调用它们.
顺便说一句,这在FAQ中都有解释,还有一些额外的好感.
如果你有一些默认函数,你想调用而不是引发错误,很明显如何用if/ elif/ else链来做,但是你如何用dict地图做呢?您可以通过将默认函数放入except块中来实现,但有一种更简单的方法:只需使用dict.get方法:
def do_stuff(x, *args):
return func_map.get(x, do_default)(*args)
Run Code Online (Sandbox Code Playgroud)