在 Python 中转置矩阵 [英] Transpose a matrix in Python
问题描述
我正在尝试用 Python 创建一个矩阵转置函数.矩阵是一个二维数组,表示为整数列表的列表.例如下面是一个2X3的矩阵(即矩阵的高为2,宽为3):
A=[[1, 2, 3],[4, 5, 6]]
要转置的第i个索引中的第j个项目应该成为第j个索引中的第i个项目.以下是上述示例的转置方式:
<预><代码>>>>转置([[1, 2, 3],[4, 5, 6]])[[1, 4],[2, 5],[3, 6]]>>>转置([[1, 2],[3, 4]])[[1, 3],[2, 4]]我该怎么做?
您可以使用 zip
和 *
得到矩阵的转置:
如果您希望返回的列表是列表列表:
<预><代码>>>>[list(x) for x in zip(*lis)][[1, 4, 7], [2, 5, 8], [3, 6, 9]]#或者>>>地图(列表,zip(*lis))[[1, 4, 7], [2, 5, 8], [3, 6, 9]]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):
A=[[1, 2, 3],
[4, 5, 6]]
To be transposed 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:
>>> 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?
You can use zip
with *
to get transpose of a matrix:
>>> 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]]
这篇关于在 Python 中转置矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!