I am trying to create a matrix transpose function for python but I can\'t seem to make it work. Say I have
theArray = [[\'a\',\'b\',\'c\'],[\'d\',\'e\',\'f\
Python 2:
>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> zip(*theArray)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
Python 3:
>>> [*zip(*theArray)]
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
If you want to transpose a matrix like A = np.array([[1,2],[3,4]]), then you can simply use A.T, but for a vector like a = [1,2], a.T does not return a transpose! and you need to use a.reshape(-1, 1), as below
import numpy as np
a = np.array([1,2])
print('a.T not transposing Python!\n','a = ',a,'\n','a.T = ', a.T)
print('Transpose of vector a is: \n',a.reshape(-1, 1))
A = np.array([[1,2],[3,4]])
print('Transpose of matrix A is: \n',A.T)
Python Program to transpose matrix:
row,col = map(int,input().split())
matrix = list()
for i in range(row):
r = list(map(int,input().split()))
matrix.append(r)
trans = [[0 for y in range(row)]for x in range(col)]
for i in range(len(matrix[0])):
for j in range(len(matrix)):
trans[i][j] = matrix[j][i]
for i in range(len(trans)):
for j in range(len(trans[0])):
print(trans[i][j],end=' ')
print(' ')
You may do it simply using python comprehension.
arr = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
]
transpose = [[arr[y][x] for y in range(len(arr))] for x in range(len(arr[0]))]
To complete J.F. Sebastian's answer, if you have a list of lists with different lengths, check out this great post from ActiveState. In short:
The built-in function zip does a similar job, but truncates the result to the length of the shortest list, so some elements from the original data may be lost afterwards.
To handle list of lists with different lengths, use:
def transposed(lists):
if not lists: return []
return map(lambda *row: list(row), *lists)
def transposed2(lists, defval=0):
if not lists: return []
return map(lambda *row: [elem or defval for elem in row], *lists)
def transpose(matrix):
listOfLists = []
for row in range(len(matrix[0])):
colList = []
for col in range(len(matrix)):
colList.append(matrix[col][row])
listOfLists.append(colList)
return listOfLists