循环使用python函数并以矩阵形式保存输入和函数值

2024-09-29 01:21:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数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)]

这给了我正确的格式,但只评估了其中一个场景。你知道吗

任何指导都是非常感谢的。谢谢!你知道吗


Tags: 函数inforrange向量resultsx1x2
2条回答

以下是可能对您有所帮助的程序:

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'],
               .
               .
               .

相关问题 更多 >