1

我想在 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依此类推。但是我的代码只创建一个函数,并执行由来自constants[lasti]. inps它给了我以下结果:

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

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

4

1 回答 1

1

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

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.]])]
于 2020-11-25T09:29:49.127 回答