How can I solve the of transpose of a matrix in single line in python?

Question:

A two dimensional matrix can be represented in Python row-wise, as a list of lists: Each inner list represents one row of the matrix. For instance, the matrix

1  2  3
4  5  6 

would be represented as [[1,2,3],[4,5,6]].

The transpose of a matrix makes each row into a column. For instance, the transpose of the matrix above is

1  4  
2  5
3  6

Write a Python function transpose(m) that takes as input a two dimensional matrix using this row-wise representation and returns the transpose of the matrix using the same representation.

Here are some examples to show how your function should work. You may assume that the input to the function is always a non-empty matrix.

>>> transpose([[1,4,9]])
[[1], [4], [9]]

>>> transpose([[1,3,5],[2,4,6]])
[[1,2], [3,4], [5,6]]
0 
>>> transpose([[1,1,1],[2,2,2],[3,3,3]])
[[1,2,3], [1,2,3], [1,2,3]]
Asked By: Kumar Ajay

||

Answers:

import math
def transpose(m):
 result=[[[m[j][i] for j in range (len(m))] for i in range (len(m[0]))]
 for r in result:
  print(r)

output:

>>>transpose([[2,4,6],[7,8,9],[3,6,7]])
[[2,7,3],[4,8,6],[6,9,7]]
Answered By: Kumar Ajay
def transpose(m):
   rez = [[[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]]
   for row in rez:
      print(row)

   transpose([[1,4,9]])
Answered By: IWTBDA

This is a great question, why does it have no rated answers?
This is an ideal case for using some advanced slicing:

def transpose(M):
    n = len(M[0])
    L = sum(M, [])
    return [L[i::n] for i in range(n)]

If you need speed, you should use itertools.chain instead of sum:

from itertools import chain

def transpose2(M):
    n = len(M[0])
    L = list(chain(*M))
    return [L[i::n] for i in range(n)]

I ran some tests on an old mac (2011) and these were the timings:
(transpose0 is for comparison)

def transpose0(M):
    return [[M[j][i] for j in range (len(M))] for i in range (len(M[0]))]

5x5 matrix:
%timeit transpose(M):  2.67 µs µs ...
%timeit transpose2(M): 2.94 µs ...
%timeit transpose0(M): 6.96 µs ...

10x10 matrix:
%timeit transpose(M):   6.25 µs ...
%timeit transpose2(M):  5.83 µs ...
%timeit transpose0(M): 19.1 µs ...

100x100 matrix:
%timeit transpose(M):  2.11 ms ...
%timeit transpose2(M):  194 µs ...
%timeit transpose0(M): 1.21 ms ...

For matrices smaller than 7×7, sum is faster. For larger matrices, you want itertools.chain. But honestly, for any serious work, I’d recommend numpy.

Answered By: Hermen

I may not understand the problem:

>>> a = [[1,2,3],[4,5,6]]
>>> print(list(zip(*a)))
[(1, 4), (2, 5), (3, 6)]
Answered By: Charles Merriam
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.