在 Python 中转置矩阵
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17037566/
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
Transpose a matrix in Python
提问by Asher Garland
I'm trying to create a matrix transpose function in Python. A matrix is a two dimensional array, represented as a list of lists of integers. For example, the following is a 2X3 matrix (meaning the height of the matrix is 2 and the width is 3):
我正在尝试在 Python 中创建一个矩阵转置函数。矩阵是一个二维数组,表示为整数列表的列表。例如下面是一个2X3的矩阵(即矩阵的高为2,宽为3):
A=[[1, 2, 3],
[4, 5, 6]]
To be transposed the the jth item in the ith index should become the ith item in the jth index. Here's how the above sample would look transposed:
要转置,第 i 个索引中的第 j 个项目应成为第 j 个索引中的第 i 个项目。以下是上述示例的转置方式:
>>> transpose([[1, 2, 3],
[4, 5, 6]])
[[1, 4],
[2, 5],
[3, 6]]
>>> transpose([[1, 2],
[3, 4]])
[[1, 3],
[2, 4]]
How can I do this?
我怎样才能做到这一点?
回答by Asher Garland
If we wanted to return the same matrix we would write:
如果我们想返回相同的矩阵,我们会写:
return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]
What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:
它的作用是遍历矩阵 m,遍历每一行并返回每一列中的每个元素。所以顺序是这样的:
[[1,2,3],
[4,5,6],
[7,8,9]]
Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:
现在对于问题 3,我们想要逐列进行,返回每行中的每个元素。所以顺序是这样的:
[[1,4,7],
[2,5,8],
[3,6,9]]
Therefore just switch the order in which we iterate:
因此只需切换我们迭代的顺序:
return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]
回答by Ashwini Chaudhary
You can use zipwith *to get transpose of a matrix:
您可以使用zipwith*来获得矩阵的转置:
>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
If you want the returned list to be a list of lists:
如果您希望返回的列表是列表列表:
>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
回答by Klaus-Dieter Warzecha
Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)
懒惰并使用 NumPy 数组的转置函数有奖吗?;)
import numpy as np
a = np.array([(1,2,3), (4,5,6)])
b = a.transpose()

