Python中的矩阵转置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4937491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matrix Transpose in Python
提问by Julio Diaz
I am trying to create a matrix transpose function for python but I can't seem to make it work. Say I have
我正在尝试为 python 创建一个矩阵转置函数,但我似乎无法让它工作。说我有
theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
and I want my function to come up with
我希望我的函数能够提出
newArray = [['a','d','g'],['b','e','h'],['c', 'f', 'i']]
So in other words, if I were to print this 2D array as columns and rows I would like the rows to turn into columns and columns into rows.
所以换句话说,如果我要将这个二维数组打印为列和行,我希望行变成列,列变成行。
I made this so far but it doesn't work
到目前为止我做了这个,但它不起作用
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
采纳答案by jfs
Python 2:
蟒蛇2:
>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> zip(*theArray)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
Python 3:
蟒蛇3:
>>> [*zip(*theArray)]
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
回答by Ned Batchelder
The problem with your original code was that you initialized transpose[t]at every element, rather than just once per row:
原始代码的问题在于您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
This works, though there are more Pythonic ways to accomplish the same things, including @J.F.'s zipapplication.
这有效,尽管有更多 Pythonic 方法可以完成相同的事情,包括 @JF 的zip应用程序。
回答by Asterisk
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)
回答by bigjim
If your rows are not equal you can also use map:
如果您的行不相等,您还可以使用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 mapchanged, itertools.zip_longestcan be used instead:
Source: What's New In Python 3.0
编辑:在 Python 3 中,功能已map更改,itertools.zip_longest可以改为使用:
来源: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')]
回答by Franck Dernoncourt
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:
要完成 JF Sebastian 的回答,如果您有不同长度的列表列表,请查看来自 ActiveState 的这篇很棒的文章。简而言之:
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.
内置函数 zip 做类似的工作,但将结果截断为最短列表的长度,因此原始数据中的某些元素可能会丢失。
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)
回答by sqwerl
>>> 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.
列表生成器使用列表项而不是元组创建一个新的二维数组。
回答by leetNightshade
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.
“最佳”答案已经提交,但我想我会补充一点,您可以使用嵌套列表推导式,如Python 教程中所示。
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 ] ) ) ]
回答by roo.firebolt
#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'
回答by Irshad Bhat
Much easier with numpy:
使用 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')
回答by chaitanya
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)

