Robin Kramer-ten Have
Robin Kramer-ten Have

Reputation: 888

Append output function to multiple lists

I want to execute a function with different parameter values. I have the following snippet of code which works perfectly well:

tau = np.arange(2,4.01,0.1)
R = []
P = []
T = []
L = []
D = []
E = []
Obj = []
for i, tenum in enumerate(tau):
    [r, p, t, l, d, e, obj] = (foo.cvxEDA(edaN, 1./fs, tenum, 0.7, 10.0, 0.0008, 0.01))
    R.append(r)
    P.append(p)
    T.append(t)
    L.append(l)
    D.append(d)
    E.append(e)
    Obj.append(obj)

However, I was wondering though: Is there an easier way to accomplish this?


I have tried using res.append(foo.cvxEDA(edaN, 1./fs, tenum, 0.7, 10.0, 0.0008, 0.01) but res[1] returns <generator object <genexpr> at 0x046E7698>.

Upvotes: 0

Views: 562

Answers (2)

Arthur Tacca
Arthur Tacca

Reputation: 9988

You can turn a generator object into a list object by just passing it to the list() function so maybe this will do what you want:

res = []
for i, tenum in enumerate(tau):
   res.append(list(foo.cvxEDA(edaN, 1./fs, tenum, 0.7, 10.0, 0.0008, 0.01)))

Even shorter with a list comprehension:

res = [list(foo.cvxEDA(edaN, 1./fs, tenum, 0.7, 10.0, 0.0008, 0.01)) for i, tenum in enumerate(tau)]

Either way, this leaves res transposed compared to what you want (thinking of it as a matrix). You can fix that with a call to zip:

res_tr = zip(*res)
R, P, T, L, D, E, Obj = res_tr

Edit: Shortest of all, you can avoid building the intermediate list with a generator expression passed directly to zip():

R, P, T, L, D, E, Obj = zip(*(list(foo.cvxEDA(edaN, 1./fs, tenum, 0.7, 10.0, 0.0008, 0.01)) for tenum in tau))

One final note: In all of these, you can replace "for i, tenum in enumerate(tau)" with "for tenum in tau" since you don't seem to be using i.

Upvotes: 3

Alex
Alex

Reputation: 1151

tau = np.arange(2,4.01,0.1)
results = [[] for _ in range(7)]
for i, tenum in enumerate(tau):
    data = foo.cvxEDA(edaN, 1./fs, tenum, 0.7, 10.0, 0.0008, 0.01)
    for r,d in zip(results, data):
        r.append(d)
r, p, t, l, d, e, _obj = results

Upvotes: 3

Related Questions