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\
>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> [list(i) for i in zip(*theArray)]
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']]
the list generator creates a new 2d array with list items instead of tuples.
The problem with your original code was that you initialized transpose[t]
at every element, rather than just once per row:
def matrixTranspose(anArray):
transposed = [None]*len(anArray[0])
for t in range(len(anArray)):
transposed[t] = [None]*len(anArray)
for tt in range(len(anArray[t])):
transposed[t][tt] = anArray[tt][t]
print transposed
This works, though there are more Pythonic ways to accomplish the same things, including @J.F.'s zip
application.
If your rows are not equal you can also use map
:
>>> uneven = [['a','b','c'],['d','e'],['g','h','i']]
>>> map(None,*uneven)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]
Edit: In Python 3 the functionality of map
changed, itertools.zip_longest
can be used instead:
Source: What’s New In Python 3.0
>>> import itertools
>>> uneven = [['a','b','c'],['d','e'],['g','h','i']]
>>> list(itertools.zip_longest(*uneven))
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]
you can try this with list comprehension like the following
matrix = [['a','b','c'],['d','e','f'],['g','h','i']]
n = len(matrix)
transpose = [[row[i] for row in matrix] for i in range(n)]
print (transpose)
a=[]
def showmatrix (a,m,n):
for i in range (m):
for j in range (n):
k=int(input("enter the number")
a.append(k)
print (a[i][j]),
print('\t')
def showtranspose(a,m,n):
for j in range(n):
for i in range(m):
print(a[i][j]),
print('\t')
a=((89,45,50),(130,120,40),(69,79,57),(78,4,8))
print("given matrix of order 4x3 is :")
showmatrix(a,4,3)
print("Transpose matrix is:")
showtranspose(a,4,3)
def transpose(matrix):
x=0
trans=[]
b=len(matrix[0])
while b!=0:
trans.append([])
b-=1
for list in matrix:
for element in list:
trans[x].append(element)
x+=1
x=0
return trans