'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)
Solution 1:[1]
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)]
Solution 2:[2]
import numpy as np
matrix = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]] )
print(matrix.T)
without using numpy
Edit: for Both Python2 and Python3
Python3
[*zip(*matrix)]
Python2
zip(*matrix)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Netwave |
| Solution 2 |
