0

Consider the following list in python:

[[[1, 2], [3, 4], [5, 6], [7, 8]],
 [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']],
 [[21, 22], [23, 24], [25, 26], [27, 28]]]

The top level list contains 3 list values which in-turn consists of 4 individual lists. I need to arrange these this lists in the following order:

[[1, 2, 'a', 'b', 21, 22],
 [3, 4, 'c', 'd', 23, 24],
 [5, 6, 'e', 'f', 25, 26],
 [7, 8, 'g', 'h', 27, 28]]

I have tried to implement this requirement using itertools, for loops, list comprehension etc but was unable to get it. Could you provide me the necessary python code capable of doing this requirement?

2 Answers 2

2

You need to use zip() here, then flatten out the resulting tuples with sublists:

[[i for sub in combo for i in sub] for combo in zip(*inputlist)]

Demo:

>>> inputlist = [[[1, 2], [3, 4], [5, 6], [7, 8]],
...  [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']],
...  [[21, 22], [23, 24], [25, 26], [27, 28]]]
>>> [[i for sub in combo for i in sub] for combo in zip(*inputlist)]
[[1, 2, 'a', 'b', 21, 22], [3, 4, 'c', 'd', 23, 24], [5, 6, 'e', 'f', 25, 26], [7, 8, 'g', 'h', 27, 28]]
Sign up to request clarification or add additional context in comments.

Comments

1

Using itertools with map:

>>> from itertools import chain, izip, starmap
>>> map(list, starmap(chain, izip(*lst)))
[[1, 2, 'a', 'b', 21, 22],
 [3, 4, 'c', 'd', 23, 24],
 [5, 6, 'e', 'f', 25, 26],
 [7, 8, 'g', 'h', 27, 28]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.