l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The result I"m looking for is
r = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
r = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
map(list, zip(*l)) --> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
For python 3.x users can use
list(map(list, zip(*l))) # short circuits at shortest nested list if table is jagged list(map(list, itertools.zip_longest(*l, fillvalue=None))) # discards no data if jagged and fills short nested lists with None
There are two things we need to know to understand what"s going on:
zipexpects an arbitrary number of arguments each of which must be iterable. E.g.
zip([1, 2], [3, 4], [5, 6]).
fsuch that each element in
argsis a separate positional argument of
itertools.zip_longestdoes 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.
R for Everyone: Advanced Analytics and Graphics. ...
In the last decade, we have seen the impact of exponential advances in technology on the way we work, shop, communicate, and think. At the heart of this change is our ability to collect and gain insig...
Deep Learning for Coders with fastai and PyTorch: AI Applications Without a PhD. Deep learning is often seen as the exclusive domain of math PhDs and big tech companies. But as this how-to guide sh...
Why this Book? Hadoop has been the base for most of the emerging technologies in today’s big data world. It changed the face of distributed processing by using commodity hardware for large data set...