Python中的matrix转置
我正在尝试为python创build一个matrix转置函数,但我似乎无法使其工作。 说我有
theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
我想让我的function提出来
newArray = [['a','d','g'],['b','e','h'],['c', 'f', 'i']]
换句话说,如果我打印这个二维数组作为列和行,我希望行变成列和列成行。
我做到这一点,但它不工作
def matrixTranspose(anArray): transposed = [None]*len(anArray[0]) for t in range(len(anArray)): for tt in range(len(anArray[t])): transposed[t] = [None]*len(anArray) transposed[t][tt] = anArray[tt][t] print transposed
>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']] >>> zip(*theArray) [('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
>>> 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']]
列表生成器创build一个新的2d数组而不是元组。
如果你的行不相同,你也可以使用map
:
>>> uneven = [['a','b','c'],['d','e'],['g','h','i']] >>> map(None,*uneven) [('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]
编辑:在Python 3中, map
的function已更改,可以使用itertools.zip_longest
:
来源: Python 3.0中的新function
>>> 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')]
要完成JF Sebastian的回答,如果你有一个不同长度的列表列表,请查看ActiveState中的这篇文章 。 简而言之:
内置函数zip做了一个类似的工作,但是将结果截断为最短列表的长度,所以原来数据中的某些元素可能会丢失。
要处理不同长度的列表,请使用:
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)
“最好”的答案已经提交,但我想补充一点,你可以使用嵌套列表parsing,如在Python教程中看到的。
以下是如何获得转置数组:
def matrixTranspose( matrix ): if not matrix: return [] return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]
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')
你原来的代码的问题是,你在每个元素初始化transpose[t]
,而不是每行一次:
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
虽然有更多Pythonic方法来完成相同的事情,包括@ JF的zip
应用程序,但这是有效的。
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)
#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'
我遵循这些提示的好build议来转置一个matrix。 我很难得到正确的输出,但最终我做到了。 但是,我没有弄清楚为什么我的第一个解决scheme(A)不能解决问题(我花了几个小时,真正的解决这个问题!)。 代码如下:
# Matrix to be transposed X = [[12, 7, 2, 4, 6], [4, 5, 7, 2, 4], [3, 8, 12, 7, 2], [6 ,7, 3, 8, 12]] # initialize the transposed matrix # initial A with zeros row = [0 for i in range(len(X))] transposed1 = [row] * (len(X[0])) # initial B with zeros transposed2 = [] for i in range(len(X[0])): transposed2.append([0] * len(X)) # Print the initial matrices print transposed1 print transposed2 # iterate through rows (i) and columns (j) for i in range(len(X)): for j in range(len(X[0])): transposed1[j][i] = X[i][j] print transposed
此代码的不正确(不需要)输出是:
>>> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [[6, 4, 2, 12], [6, 4, 2, 12], [6, 4, 2, 12], [6, 4, 2, 12], [6, 4, 2, 12]]
然后,我改变了转置1,转换2,反之亦然。 这一次(期望的)输出是:
>>> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [[12, 4, 3, 6], [7, 5, 8, 7], [2, 7, 12, 3], [4, 2, 7, 8], [6, 4, 2, 12]]
正如你所看到的,初始化的零matrix看起来是一样的,但结果是不同的,这取决于如何生成零matrix。 你能弄清楚为什么?
欢呼声,Risto-Matti
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)
这一个将保留矩形形状,以便随后的转置将得到正确的结果:
import itertools def transpose(list_of_lists): return list(itertools.izip_longest(*list_of_lists,fillvalue=' '))
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
a = [] m=int(input("enter no of rows in the matrix")) n=int(input("enter no of columns in the matrix")) for i in range(0,m) : a.append([]) for j in range(0,n) : a[i].append((input("enter element"))) print(a) trans =[] for i in range(0,m) : trans.append([]) for j in range(0,n) : trans[i].append(a[j][i]) print("tranpose matrix :",trans)
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
`
def transpose(m): return(list(map(list,list(zip(*m)))))