# 在 Python 中转置矩阵

Vaibhav Vaibhav 2023年1月30日

## 在 Python 中转置矩阵

``````def transpose(matrix):
if matrix == None or len(matrix) == 0:
return []

result = [[None for i in range(len(matrix))] for j in range(len(matrix[0]))]

for i in range(len(matrix[0])):
for j in range(len(matrix)):
result[i][j] = matrix[j][i]

return result

def print_matrix(matrix):
for row in matrix:
print(*row)

array = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
result = transpose(array)
print_matrix(result)
``````

``````1 6 11
2 7 12
3 8 13
4 9 14
5 10 15
``````

``````def transpose(matrix):
if matrix == None or len(matrix) == 0:
return []

return [[matrix[i][j] for i in range(len(matrix))] for j in range(len(matrix[0]))]

def print_matrix(matrix):
for row in matrix:
print(*row)

array = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
result = transpose(array)
print_matrix(result)
``````

``````1 6 11
2 7 12
3 8 13
4 9 14
5 10 15
``````

## 在 Python 中使用 `NumPy` 模块转置矩阵

`NumPy` 是一个 Python 包，它具有丰富的实用程序，可用于处理大型多维矩阵和数组，并对它们执行复杂而直接的数学运算。这些实用程序不仅对输入是动态的，而且高度优化和快速。

``````import numpy as np

array = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
array = np.array(array)
print(array.T)  # First Method
print(array.transpose())  # Second Method
``````

``````[[ 1  6 11]
[ 2  7 12]
[ 3  8 13]
[ 4  9 14]
[ 5 10 15]]
[[ 1  6 11]
[ 2  7 12]
[ 3  8 13]
[ 4  9 14]
[ 5 10 15]]
``````

`transpose()` 接受一个 `axes` 参数，该参数可用于对 `NumPy` 数组执行一些很酷的转置修改。要详细了解此方法，请单击此处

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.