繁体   English   中英

遍历python函数并以矩阵格式保存输入和函数值

[英]Looping through python function and savings inputs and function value in a matrix format

我有一个函数f,并且尝试在x,y和z上求值:

x = range(60,70)
y = range(0,5)
z = ["type1", "type2"]

results = [f(v,w,j) for v in x for w in y for j in z]

现在,“结果”是一个很长的向量,但是我想得到一个看起来像这样的矩阵:

x1 y1 z1 f(x1,y1,z1)
x2 y1 z1 f(x2,y1,z1)
...
x9 y1 z1 f(x9,y1,z1)
x1 y2 z1 f(x1,y2,z1)
x2 y2 z1 f(x2,y2,z1)
...
x9 y2 z1 f(x9,y2,z1)
x1 y1 z2 f(x1,y1,z2)
...

涵盖所有可能的组合。 到目前为止,我已经尝试过了:

z = []
for v in x:
    for w in y:
        for j in z:
            z = [v, w, j, f(v,w,j)]

这给了我正确的格式,但只评估了其中一种情况。

任何指导都是值得的。 谢谢!

这是可以帮助您的程序:

x = range(60, 70)
y = range(0,5)
z = ["type1", "type2"]
ans = []
for i in x:
    for j in y:
        for k in z:
            ans.append([i, j, k, f(i, j, k)])

print(ans)

您可以结合使用numpy和porduct获得类似答案的矩阵。

from itertools import product

x = range(60,70)
y = range(0,5)
z = ["type1", "type2"]

l = (x,y,z)
res = list(product(*l))
res

输出:

[(60, 0, 'type1'),
 (60, 0, 'type2'),
 (60, 1, 'type1'),
 (60, 1, 'type2'),
 (60, 2, 'type1'),
 (60, 2, 'type2'),
 (60, 3, 'type1'),
 (60, 3, 'type2'),
 (60, 4, 'type1'),
 (60, 4, 'type2'),
 (61, 0, 'type1'),
 (61, 0, 'type2'),
 (61, 1, 'type1'),
.
.
.

要变成像numpy这样的矩阵:

import numpy as np

res = np.array(res).reshape(-1,len(l))

输出:

array([['60', '0', 'type1'],
       ['60', '0', 'type2'],
       ['60', '1', 'type1'],
       ['60', '1', 'type2'],
       ['60', '2', 'type1'],
       ['60', '2', 'type2'],
       ['60', '3', 'type1'],
       ['60', '3', 'type2'],
       ['60', '4', 'type1'],
               .
               .
               .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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