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?
[x for i in np.arange(3) for x in [f1(i), f2(i)]]
使用具有两个for
子句的列表理解。
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?
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.