# 在 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.