Transpose a matrix in Python [duplicate]
Asked Answered
I

3

30

I'm trying to create a matrix transpose function in Python. A matrix is a two dimensional array, represented as a list of lists of integers. For example, the following is a 2X3 matrix (meaning the height of the matrix is 2 and the width is 3):

A=[[1, 2, 3],
   [4, 5, 6]]

To be transposed the jth item in the ith index should become the ith item in the jth index. Here's how the above sample would look transposed:

>>> transpose([[1, 2, 3],
               [4, 5, 6]])
[[1, 4],
[2, 5],
[3, 6]]
>>> transpose([[1, 2],
               [3, 4]])
[[1, 3],
[2, 4]]

How can I do this?

Ignacia answered 11/6, 2013 at 6:11 Comment(1)
You can find an answer here: #6474179Kazak
E
110

You can use zip with * to get transpose of a matrix:

>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis  = [[1,2,3], 
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want the returned list to be a list of lists:

>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Etui answered 11/6, 2013 at 6:13 Comment(2)
In Python 3, map returns an iterator, so to get a list from the last solution you need list(map(list, zip(*lis))) or [*map(list, zip(*lis))].Ruzich
Can you explain more on how the * works in zip(*lis)Aliment
M
28

Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)

import numpy as np

a = np.array([(1,2,3), (4,5,6)])

b = a.transpose()
Micronucleus answered 11/6, 2013 at 10:54 Comment(2)
Your answer is not correct because of the given skeleton function. This answer must be done using list comprehension. The answer below is correct. Good information though.Ignacia
Not only you're importing a huge library to do something that can be achieved with one line of pure python, your answer is also technically wrong because the output is not a list of list as shown in the question, but a numpy array. So the answer is longer and slower, because you have to convert to a numpy array, transpose, and convert back.Apodal
I
13

If we wanted to return the same matrix we would write:

return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]

What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:

[[1,2,3],
[4,5,6],
[7,8,9]]

Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:

[[1,4,7],
[2,5,8],
[3,6,9]]

Therefore just switch the order in which we iterate:

return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]
Ignacia answered 11/6, 2013 at 6:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.