0

How to convert this:

[[[1,2,3], ['a','b','c']], [[4,5], ['d','e']], [[6,7,8,9], ['f','g','h','i']]]

to this:

[[1,2,3,4,5,6,7,8,9], ['a','b','c','d','e','f','g','h','i']]

Knowing python, there must be some way using zip and list comprehensions.

Serbitar
  • 2,134
  • 19
  • 25
  • Combine `zip` with [Flattening a shallow list in Python](http://stackoverflow.com/q/406121), by the looks of it. – Martijn Pieters Jul 14 '14 at 10:50
  • Closing this as a dupe, as there isn't anything novel enough here apart from looping over the `zip(*inputlist)` output first, then applying the other answer to every element from that. – Martijn Pieters Jul 14 '14 at 10:51

1 Answers1

3

Looks like a task for zip and itertools.chain.from_iterable().

data = [[[1,2,3], ['a','b','c']], [[4,5], ['d','e']], [[6,7,8,9], ['f','g','h','i']]]
list(zip(*data))

This will give you

[([1, 2, 3], [4, 5], [6, 7, 8, 9]), (['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i'])]

Now apply chain.from_iterable for the inner lists:

data = [[[1,2,3], ['a','b','c']], [[4,5], ['d','e']], [[6,7,8,9], ['f','g','h','i']]]
print([list(itertools.chain.from_iterable(inner)) for inner in zip(*data)])
Matthias
  • 12,873
  • 6
  • 42
  • 48