作为this question的后续措施:
我有两个看起来像这样的函数:
def abc(a,b):
return a+b
def cde(c,d):
return c+d
我想将其分配给这样的字典:
functions = {'abc': abc(a,b), 'cde': cde(c,d)}
我可以这样做,但是会在“ 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个参数怎么办?
最佳答案
单独创建一个args
序列,并使用splat运算符(*
):
>>> 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