Reputation: 452
def f1(x): return [(x+1)*2-1, (x+1)*2-1]
def f2(x): return [(x+1)*2, (x+1)*2]
[[f1(i), f2(i)] for i in np.arange(3)]
This is the code to generate a list
of 3 list-pairs elements:
[[[1, 1], [2, 2]], [[3, 3], [4, 4]], [[5, 5], [6, 6]]]
However, I would like to obtain a list
like below with one line of for
loop.
[[1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6]]
This is how it works with multi-lines:
n = []
for i in np.arange(3):
n += [f1(i), f2(i)]
It's like trying to compose 2 elements per time where I don't know how to achieve +=
for one line of code. How can I do that?
Upvotes: 1
Views: 994
Reputation: 280182
[x for i in np.arange(3) for x in [f1(i), f2(i)]]
Use a list comprehension with two for
clauses.
Upvotes: 2
Reputation: 452
I could do something like this:
[f1(i) for i in np.arange(3)] + [f2(i) for i in np.arange(3)]
But is there any better way?
Upvotes: 0