python - 如何使用列表推导将函数列表应用于参数列表
问题描述
我有一个函数可以创建一个新数组,其中每个项目都是函数列表中函数 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
解决方案
我认为您在代码中打错了字,但我想您想写:
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), ...]
推荐阅读
- events - jupyterlab 按钮事件不起作用
- javascript - 为什么我的表单输出 NaN?
- tensorflow - 如何使用 tf.layers 类而不是函数
- pdfbox - 如何使用 PDFBox 从 PDF 文件中删除覆盖?
- c# - 为什么我的 ASP.NET ListBox 没有填充结果?
- python - 如何将两个列表合并到 Python 中的字典中?Dict 和 Zip 不起作用
- r - 使用 mutate() 返回关于无法修改的错误,因为它是一个分组变量
- python-2.7 - 如何在 3D 数组上应用 mean_squared_error
- php - 如何强制客户在 Magento 中注销
- perl - 错过了哪些模块?