首页 > 解决方案 > 如何使用列表推导将函数列表应用于参数列表

问题描述

我有一个函数可以创建一个新数组,其中每个项目都是函数列表中函数 f(x) 的结果。
例如,
x= [1,2,3]
interFunctions = [f1,f2,f3]
我希望结果是 y = [f1(x[0]),f2(x[1]),f3(x [2])]
第一个函数工作正常,但是,我想使用列表推导来完成这个过程,这样我的代码就不会那么慢了。凭借我的基本技能,我尝试使用我的第二个函数,它只返回一个项目,我无法理解这个列表理解如何为多个列表工作,有人可以向我解释一下吗?
第一个功能

def makeNewYaxisLstofArrays(newXaxisListofArray,lstInterFuncs):        
    for f in lstInterFuncs:
        data = []   
        for x in newXaxisListofArray:
            data.append(f(x))
    return data

尝试使用列表理解

def makeNewYaxisLstofArrays(newXaxisListofArray,lstInterFuncs):
    for f in lstInterFuncs:
        data = [f(x)for x in newXaxisListofArray]
        for x in newXaxisListofArray:            
    return data

标签: pythonlist-comprehension

解决方案


我认为您在代码中打错了字,但我想您想写:

def makeNewYaxisLstofArrays(newXaxisListofArray,lstInterFuncs):
    for f in lstInterFuncs:
        data = [f(x) for x in newXaxisListofArray]
        # for x in newXaxisListofArray: <- I guess it shouldn't be here
    return data

您的代码的问题在于您正在data为每个函数创建。您的代码从 中获取第一个函数lstInterFuncs并将其应用于 中的每个元素newXaxisListofArray。这样,在循环的第一次运行中(对于来自 的第一个元素lstInterFuncs),您将得到[f1(x1), f1(x2),...]. f2然后,为:等创建列表[f2(x1), f2(x2),...]。请注意,每次覆盖data变量时。最后,您的函数返回最后一个函数的列表:([f3(x1), f3(x2), ...]假设您有 3 个函数)

我认为你应该同时迭代两者。在我看来,您可能想要使用一个zip()函数 -> 它可以同时迭代两个(或更多)列表并将它们打包成一个元组:

def makeNewYaxisLstofArrays(newXaxisListofArray,lstInterFuncs):
    data = [f(x) for f, x in zip(lstInterFuncs, newXaxisListofArray)]
    return data

代码将同时迭代函数和值,所以你会得到[f1(x1), f2(x2), ...]


推荐阅读