为每个列表项调用不同的函数

nat*_*ill 3 python

假设我有一个这样的列表:

[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

以及这样的函数列表:

[a, b, c, d]
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法来获得这个输出?有类似的东西zip,但功能和参数?

[a(1), b(2), c(3), d(4)]
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 10

使用zip()和列表推导将每个函数应用于其配对参数:

arguments = [1, 2, 3, 4]
functions = [a, b, c, d]

results = [func(arg) for func, arg in zip(functions, arguments)]
Run Code Online (Sandbox Code Playgroud)

演示:

>>> def a(i): return 'function a: {}'.format(i)
...
>>> def b(i): return 'function b: {}'.format(i)
...
>>> def c(i): return 'function c: {}'.format(i)
...
>>> def d(i): return 'function d: {}'.format(i)
...
>>> arguments = [1, 2, 3, 4]
>>> functions = [a, b, c, d]
>>> [func(arg) for func, arg in zip(functions, arguments)]
['function a: 1', 'function b: 2', 'function c: 3', 'function d: 4']
Run Code Online (Sandbox Code Playgroud)