Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list (without nested list) directly from a list comprehension [duplicate]

I want to return a list with the interleaved elements of two lists directly from the list comprehension - without use a next step to flaten the result. Is it possible?

alist1_temp=[1, 4,2]
alist2_temp=[3, 7,4]
t=[[x,y] for x,y in zip(alist1_temp, alist2_temp)]

Return [[1, 3], [4, 7],[2, 4]]

But how can I get directly from the list-comprehension [1, 3, 4, 7, 2, 4]?

like image 514
Pedro Pinto Avatar asked Jan 06 '19 14:01

Pedro Pinto


2 Answers

Try this with just zip to get it in that order that you want:

[i for j in zip(alist1_temp, alist2_temp) for i in j]

if you don't mind the order just do:

alist1_temp + alist2_temp

or get it with itertools.chain thanks to @buran:

import itertools

list(itertools.chain(alist1_temp, alist2_temp))
like image 147
Mehrdad Pedramfar Avatar answered Oct 13 '22 01:10

Mehrdad Pedramfar


If you like numpy way of doing this, you could use this!

np.vstack((alist1_temp,alist2_temp)).flatten('F')

or you can flatten your list comprehension as well

np.array(t).flatten()
like image 38
Venkatachalam Avatar answered Oct 13 '22 01:10

Venkatachalam