简体   繁体   中英

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

I want to run a function in a for loop. 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 . 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. Then, I want to multiply the second of constants tothe second array of inps and so on. 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 . 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.]])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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