0

Given there is a list if lists like the below.

[
  [1, 2, 3],
  [4, 5],
  [6, 8, 9, 10],
  [11]
]

I hope that I can flatten the list and the output should be [1, 4, 6, 11, 2, 5, 8, 3, 9, 10]. How to implement this in Python?

link89
  • 1,064
  • 10
  • 13

3 Answers3

2

You can use the zip_longest function from the itertools module to combine these lists, and just throw away the None fillvalues

from itertools import zip_longest

list_of_lists = [
    [1, 2, 3],
    [4, 5],
    [6, 8, 9, 10],
    [11]
    ]

flat_list = []
for tup in zip_longest(*list_of_lists, fillvalue=None):
    for e in tup:
        if e is not None:
            flat_list.append(e)

print(flat_list)

Or as a list comprehension:

flat_list = [e for tup in zip_longest(*list_of_lists) for e in tup if e is not None]
nigh_anxiety
  • 1,428
  • 2
  • 4
  • 12
0
data = [[1, 2, 3],
[4, 5],
[6, 8, 9, 10],
[11]]
from itertools import zip_longest
[i for lst in zip_longest(*data) for i in lst if i is not None]

or a more complex way:

from itertools import zip_longest
from functools import reduce
list(filter(lambda x: x is not None, reduce(lambda x, y: x + y, zip_longest(*data))))

or

reduce(lambda x, y: x + tuple(i for i in y if i is not None), zip_longest(*data))

if it is ok, I can explain it

MoRe
  • 2,296
  • 2
  • 3
  • 23
0
tree = [[1, 2, 3],
        [4, 5],
        [6, 8, 9, 10],
        [11]]

stump = [
    sublist[i]
    for i in range(max(map(len, tree)))
    for sublist in tree if len(sublist) > i
    ]

print(stump) #[1, 4, 6, 11, 2, 5, 8, 3, 9, 10]
richard
  • 19
  • 2