Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose Of Matrix in Python

I am new on Python i am working on Transpose of matrix but i found it lengthy code any short procedure please!

mymatrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)] 
for myrow in mymatrix: 
    print(myrow) 
    print("\n") 
    t_matrix = zip(*mymatrix) 
for myrow in t_matrix: 
    print(myrow)
like image 536
Smith Set Avatar asked Dec 05 '22 10:12

Smith Set


2 Answers

You need to install numpy in order to import it Numpy transpose returns similar result when
applied on 1D matrix

import numpy  
mymatrix=[[1,2,3],[4,5,6]] 
print(mymatrix) 
print("\n") 
print(numpy.transpose(mymatrix)) 
like image 178
Ihtisham Ali Farooq Avatar answered Dec 28 '22 19:12

Ihtisham Ali Farooq


Use zip:

mymatrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)] 
myTransposedMatrix = list(zip(*mymatrix))

>>> myTransposedMatrix
[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
like image 37
Netwave Avatar answered Dec 28 '22 20:12

Netwave