简体   繁体   English

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

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

I want to run a function in a for loop.我想在 for 循环中运行一个函数。 Firstly, I have a list of arrays and each arry includes some constants.首先,我有一个数组列表,每个数组都包含一些常量。 These constants go to function.这些常量发挥作用。 Then, I make function and finally import arrays stored as a list into the created function.然后,我创建函数,最后将存储为列表的数组导入到创建的函数中。 At the moment it is only using the constants stored in the last array of the list storing constants.目前它只使用存储常量的列表的最后一个数组中存储的常量。 I want to create the first function using the first array of constants and run that function for the first array of inps .我想使用第一个constants数组创建第一个函数,并为第一个inps数组运行该函数。 I have checked this solution but I could not solve my issue.我已经检查了这个解决方案,但我无法解决我的问题。

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.]])]

This is my code:这是我的代码:

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)

Then, I want to get:然后,我想得到:

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

Simply, I want to multiply first value of the first array of constants to first column of first array of inps and replace it with the result.简单地说,我想将第一个constants数组的第一个值乘以第一个inps数组的第一列,并将其替换为结果。 Then, I want to multiply the second of constants tothe second array of inps and so on.然后,我想将第二个constants乘以第二个inps数组,依此类推。 But my code is creating only one function and performs the last function created by the cnstants coming from constants[lasti] for all the arrays of inps .但是我的代码只创建了一个函数,并为所有inps数组执行由来自constants[lasti]的 cnstants 创建的最后一个函数。 It is giving me the following result:它给了我以下结果:

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

In advance, I appreciate any help.在此之前,我感谢任何帮助。

Not sure you need the function at all.不确定您是否需要该功能。 This produces the output you are looking for:这会产生您正在寻找的输出:

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)

Output:输出:

[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