简体   繁体   English

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

[英]Call different function for each list item

Let's say I have a list like this: 假设我有一个这样的列表:

[1, 2, 3, 4]

And a list of functions like this: 以及这样的函数列表:

[a, b, c, d]

Is there an easy way to get this output? 有没有一种简单的方法来获得这个输出? Something like zip , but with functions and arguments? zip这样的东西,但有功能和参数?

[a(1), b(2), c(3), d(4)]

Use zip() and a list comprehension to apply each function to their paired argument: 使用zip()和列表推导将每个函数应用于其配对参数:

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

results = [func(arg) for func, arg in zip(functions, arguments)]

Demo: 演示:

>>> 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']
arguments = [1, 2, 3, 4]
functions = [a, b, c, d]

def process(func, arg):
    return func(arg)

results = map(process, functions, arguments)

define a function process to do the job, and use map to iterate the functions with its arguments 定义一个函数process来完成这项工作,并使用map来迭代functions及其arguments

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM