Transpose list of lists
Python 3:
# short circuits at shortest nested list if table is jagged:
list(map(list, zip(*l)))
# discards no data if jagged and fills short nested lists with None
list(map(list, itertools.zip_longest(*l, fillvalue=None)))
Python 2:
map(list, zip(*l))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Explanation:
There are two things we need to know to understand what's going on:
- The signature of zip:
zip(*iterables)
This meanszip
expects an arbitrary number of arguments each of which must be iterable. E.g.zip([1, 2], [3, 4], [5, 6])
. -
Unpacked argument lists: Given a sequence of arguments
args
,f(*args)
will callf
such that each element inargs
is a separate positional argument off
. -
itertools.zip_longest
does not discard any data if the number of elements of the nested lists are not the same (homogenous), and instead fills in the shorter nested lists then zips them up.
Coming back to the input from the question l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
, zip(*l)
would be equivalent to zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
. The rest is just making sure the result is a list of lists instead of a list of tuples.
One way to do it is with NumPy transpose. For a list, a:
>>> import numpy as np
>>> np.array(a).T.tolist()
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Or another one without zip:
>>> map(list,map(None,*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Equivalently to Jena's solution:
>>> l=[[1,2,3],[4,5,6],[7,8,9]]
>>> [list(i) for i in zip(*l)]
... [[1, 4, 7], [2, 5, 8], [3, 6, 9]]