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\
The "best" answer has already been submitted, but I thought I would add that you can use nested list comprehensions, as seen in the Python Tutorial.
Here is how you could get a transposed array:
def matrixTranspose( matrix ):
if not matrix: return []
return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]
def matrixTranspose(anArray):
transposed = [None]*len(anArray[0])
for i in range(len(transposed)):
transposed[i] = [None]*len(transposed)
for t in range(len(anArray)):
for tt in range(len(anArray[t])):
transposed[t][tt] = anArray[tt][t]
return transposed
theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
print matrixTranspose(theArray)
This one will preserve rectangular shape, so that subsequent transposes will get the right result:
import itertools
def transpose(list_of_lists):
return list(itertools.izip_longest(*list_of_lists,fillvalue=' '))
Much easier with numpy:
>>> arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> arr
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> arr.T
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
>>> theArray = np.array([['a','b','c'],['d','e','f'],['g','h','i']])
>>> theArray
array([['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']],
dtype='|S1')
>>> theArray.T
array([['a', 'd', 'g'],
['b', 'e', 'h'],
['c', 'f', 'i']],
dtype='|S1')
`
def transpose(m):
return(list(map(list,list(zip(*m)))))
`This function will return the transpose
#generate matrix
matrix=[]
m=input('enter number of rows, m = ')
n=input('enter number of columns, n = ')
for i in range(m):
matrix.append([])
for j in range(n):
elem=input('enter element: ')
matrix[i].append(elem)
#print matrix
for i in range(m):
for j in range(n):
print matrix[i][j],
print '\n'
#generate transpose
transpose=[]
for j in range(n):
transpose.append([])
for i in range (m):
ent=matrix[i][j]
transpose[j].append(ent)
#print transpose
for i in range (n):
for j in range (m):
print transpose[i][j],
print '\n'