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]
?
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))
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With