简体   繁体   中英

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

I have a function, f, and I am trying to evaluate it at x, y and 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]

Right now "results" is a long vector, but I would like to get a matrix that looks something like this:

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)
...

covering all the possible combinations. So far I have tried this:

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

which is giving me the right format, but only evaluating one of the scenarios.

Any guidance is appreciate it . Thanks!

Here is program which might help you:

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)

You can combine using numpy and porduct to get a matrix like answer.

from itertools import product

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

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

Output:

[(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'),
.
.
.

To turn into matrix like with numpy:

import numpy as np

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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