6

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]?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
Pedro Pinto
  • 125
  • 6

3 Answers3

5

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))
Mehrdad Pedramfar
  • 9,989
  • 4
  • 33
  • 55
1

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()
Venkatachalam
  • 14,895
  • 9
  • 40
  • 70
1

As you specified that you want get it from from the list-comprehension:

alist1_temp=[1,4,2]
alist2_temp=[3,7,4]
L = len(alist1_temp)+len(alist2_temp)
t = [alist2_temp[i//2] if i%2 else alist1_temp[i//2] for i in range(L)]
print(t) #prints [1, 3, 4, 7, 2, 4]
Daweo
  • 21,690
  • 3
  • 9
  • 19