【问题标题】:how to generate functions in a for loop and use them for several inputs如何在 for 循环中生成函数并将它们用于多个输入
【发布时间】:2020-11-24 12:47:37
【问题描述】:

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

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] 的cnstants 为inps 的所有数组创建的最后一个函数。 它给了我以下结果:

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

在此先感谢您的帮助。

【问题讨论】:

  • 函数应该在for循环之前定义,并在其中调用
  • @Dear LouieC,我尝试了您的解决方案,但结果仍然相同。
  • "我已经检查了这个解决方案,但我无法解决我的问题。"我不明白为什么不。当您尝试应用那里的答案中给出的建议时发生了什么?
  • 亲爱的@Karl Knechtel,根据我尝试将row=i 放入我的函数中的解决方案,但它并没有解决我的问题。
  • 你目前得到什么输出?

标签: python list function for-loop


【解决方案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.]])]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2019-02-02
    • 1970-01-01
    • 2020-03-18
    • 2011-10-25
    相关资源
    最近更新 更多