【发布时间】: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