Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose list of lists

Let's take:

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]] 

and not

r = [(1, 4, 7), (2, 5, 8), (3, 6, 9)] 

Much appreciated

like image 458
titus Avatar asked Jun 24 '11 20:06

titus


People also ask

How do you transpose a list of lists in Python?

Transpose with built-in function zip() You can transpose a two-dimensional list using the built-in function zip() . zip() is a function that returns an iterator that summarizes the multiple iterables ( list , tuple , etc.). In addition, use * that allows you to unpack the list and pass its elements to the function.

Can you have a list of list of lists in Python?

We can have a list of many types in Python, like strings, numbers, and more. Python also allows us to have a list within a list called a nested list or a two-dimensional list.


2 Answers

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:

  1. The signature of zip: zip(*iterables) This means zip expects an arbitrary number of arguments each of which must be iterable. E.g. zip([1, 2], [3, 4], [5, 6]).
  2. Unpacked argument lists: Given a sequence of arguments args, f(*args) will call f such that each element in args is a separate positional argument of f.
  3. 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.

like image 122
jena Avatar answered Sep 30 '22 20:09

jena


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]] 
like image 23
SiggyF Avatar answered Sep 30 '22 19:09

SiggyF