-1

Is there a good way to merge lists like that:

L1 = [1.1, 1.2, 1.3]

L2 = [2.1, 2.2, 2.3, 2.4]

L3 = [3.1, 3.2]

Result:

[1.1, 2.1, 3.1, 1.2, 2.2, 3.2, 1.3, 2.3, 2.4]

There should be no "None" elements in result.

Edit

Since it was marked as duplicate: I do not need a result like this:

[(1.1, 2.1, 3.1), (1.2, 2.2, 3.2), (1.3, 2.3, None), (None, 2.4, None)]

I do not need any "None" elements. And the result should be one list.

UpmostScarab
  • 960
  • 10
  • 29

2 Answers2

4

With izip_longest from itertools:

>>> from itertools import izip_longest
>>> L1 = [1.1, 1.2, 1.3]
>>> L2 = [2.1, 2.2, 2.3, 2.4]
>>> L3 = [3.1, 3.2]
>>> [x for sub in izip_longest(L1,L2,L3) for x in sub if x is not None]
[1.1, 2.1, 3.1, 1.2, 2.2, 3.2, 1.3, 2.3, 2.4]

Answer to the comment:

What if the lists have None in them?

None is the default fillvalue:

>>> list(izip_longest(L1,L2,L3))
[(1.1, 2.1, 3.1), (1.2, 2.2, 3.2), (1.3, 2.3, None), (None, 2.4, None)]

If the lists can have None in them, use a fillvalue that cannot appear in the lists. For example:

>>> list(izip_longest(L1,L2,L3,fillvalue='my_awesome_fillval'))
[(1.1, 2.1, 3.1), (1.2, 2.2, 3.2), (1.3, 2.3, 'my_awesome_fillval'), ('my_awesome_fillval', 2.4, 'my_awesome_fillval')]
timgeb
  • 76,762
  • 20
  • 123
  • 145
2

To merge the lists

L1 = [1.1, 1.2, 1.3]
L2 = [2.1, 2.2, 2.3, 2.4]
L3 = [3.1, 3.2]

you can use the following one-liner

>>>  [x for y in map(None,L1,L2,L3) for x in y if x is not None]
[1.1, 2.1, 3.1, 1.2, 2.2, 3.2, 1.3, 2.3, 2.4]
jofel
  • 3,297
  • 17
  • 31