繁体   English   中英

如何在 for 循环中生成函数并将它们用于多个输入

[英]how to generate functions in a for loop and use them for several inputs

我想在 for 循环中运行一个函数。 首先,我有一个数组列表,每个数组都包含一些常量。 这些常量发挥作用。 然后,我创建函数,最后将存储为列表的数组导入到创建的函数中。 目前它只使用存储常量的列表的最后一个数组中存储的常量。 我想使用第一个constants数组创建第一个函数,并为第一个inps数组运行该函数。 我已经检查了这个解决方案,但我无法解决我的问题。

constants=[np.array([2., 2., 2., 2.]),
           np.array([20., 40., 30., 10.])]
inps=[np.array([[1., 1., 1.],[2., 2., 2.]]),
      np.array([[3., 3., 3.],[4., 4., 4.]])]

这是我的代码:

def fun(row=i):
    row[0] = a * row[0]
    for i in constants:
        i=i.tolist()
        a = i[0]
        return row[0], row[1], row[2]
    out=[]
    for j in inps:
        j=[j]
        new = np.asarray(list(map(fun, [x for point in j for x in point])))
        out.append(new)

然后,我想得到:

out= [np.array([[2.,  1.,  1.],
                [4.,  2.,  2.]]),
      np.array([[60.,  3. ,  3. ],
                [80.,  4. ,  4. ]])]

简单地说,我想将第一个constants数组的第一个值乘以第一个inps数组的第一列,并将其替换为结果。 然后,我想将第二个constants乘以第二个inps数组,依此类推。 但是我的代码只创建了一个函数,并为所有inps数组执行由来自constants[lasti]的 cnstants 创建的最后一个函数。 它给了我以下结果:

[array([[40.,  1.,  1.],
        [80.,  2.,  2.]]),
 array([[120.,   3.,   3.],
        [160.,   4.,   4.]])]

在此之前,我感谢任何帮助。

不确定您是否需要该功能。 这会产生您正在寻找的输出:

import numpy as np


constants = [
    np.array([2.0, 2.0, 2.0, 2.0]),
    np.array([20.0, 40.0, 30.0, 10.0])]
inps = [
    np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]),
    np.array([[3.0, 3.0, 3.0], [4.0, 4.0, 4.0]]),
]


for index, inp in enumerate(inps):
    inp[:,0] *= constants[index][0]

print(inps)

输出:

[array([[2., 1., 1.],
        [4., 2., 2.]]),
 array([[60.,  3.,  3.],
        [80.,  4.,  4.]])]

暂无
暂无

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

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