本文介绍了词典中的访问功能第2部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
作为此问题的后续行动:我有2个功能看起来像这样:
As a follow-up to this question: I have 2 functions that look like this:
def abc(a,b): return a+b def cde(c,d): return c+d而且想要将它分配给这样的字典:
And I want to assign it to a dictionary like this:
functions = {'abc': abc(a,b), 'cde': cde(c,d)}我可以这样做,但是会在'cde ':
I could do this, but it would break at 'cde':
functions = {'abc':abc, 'cde':cde} functions_to_call = ['abc', 'cde'] for f in functions_to_call: a, b = 3, 4 c, d = 1, 2 if f in functions: functions[f](a, b)另外,如果cde有3个参数呢?
Also, what if cde took 3 arguments?
推荐答案使用 args 的单独序列,并使用splat运算符 * ):
Make a seperate sequence of args and use the splat operator (*):
>>> def ab(a,b): ... return a + b ... >>> def cde(c,d,e): ... return c + d + e ... >>> funcs = {'ab':ab, 'cde':cde} >>> to_call = ['ab','cde'] >>> args = [(1,2),(3,4,5)] >>> for fs, arg in zip(to_call,args): ... print(funcs[fs](*arg)) ... 3 12更多推荐
词典中的访问功能第2部分
发布评论