This question already has an answer here:
-
Transpose list of lists
10 answers
Let's say I have a SINGLE list [[1,2,3],[4,5,6]]
How do I transpose them so they will be: [[1, 4], [2, 5], [3, 6]]
?
Do I have to use the zip
function? Is the zip
function the easiest way?
def m_transpose(m):
trans = zip(m)
return trans
Using zip
and *splat
is the easiest way in pure Python.
>>> list_ = [[1,2,3],[4,5,6]]
>>> zip(*list_)
[(1, 4), (2, 5), (3, 6)]
Note that you get tuples inside instead of lists. If you need the lists, use map(list, zip(*l))
.
If you're open to using numpy
instead of a list of lists, then using the .T
attribute is even easier:
>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> print(*a)
[1 2 3] [4 5 6]
>>> print(*a.T)
[1 4] [2 5] [3 6]
You can use map with None
as the first parameter:
>>> li=[[1,2,3],[4,5,6]]
>>> map(None, *li)
[(1, 4), (2, 5), (3, 6)]
Unlike zip
it works on uneven lists:
>>> li=[[1,2,3],[4,5,6,7]]
>>> map(None, *li)
[(1, 4), (2, 5), (3, 6), (None, 7)]
>>> zip(*li)
[(1, 4), (2, 5), (3, 6)]
# ^^ 7 missing...
Then call map again with list
as the first parameter if you want the sub elements to be lists instead of tuples:
>>> map(list, map(None, *li))
[[1, 4], [2, 5], [3, 6]]
(Note: the use of map with None
to transpose a matrix is not supported in Python 3.x. Use zip_longest from itertools to get the same functionality...)
zip()
doesn't seem to do what you wanted, using zip()
you get a list
of tuples
. This should work though:
>>> new_list = []
>>> old_list = [[1,2,3],[4,5,6]]
>>> for index in range(len(old_list[0])):
... new_list.append([old_list[0][index], old_list[1][index]])
...
>>> new_list
[[1, 4], [2, 5], [3, 6]]
The exact way of use zip()
and get what you want is:
>>> l = [[1,2,3],[4,5,6]]
>>> [list(x) for x in zip(*l)]
>>> [[1, 4], [2, 5], [3, 6]]
This code use list
keyword for casting the tuples
returned by zip
into lists
.