共計 552 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,矩陣遍歷有多種方法,以下是幾種常見的方法:
- 使用嵌套循環遍歷:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(matrix[i][j])
- 使用列表推導式遍歷:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
elements = [element for row in matrix for element in row]
print(elements)
- 使用 NumPy 庫遍歷:
import numpy as np
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
np_matrix = np.array(matrix)
for row in np_matrix:
for element in row:
print(element)
- 使用 NumPy 庫的 flat 屬性遍歷:
import numpy as np
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
np_matrix = np.array(matrix)
for element in np_matrix.flat:
print(element)
這些方法可以根據具體需求選擇適合的方式遍歷矩陣。
丸趣 TV 網 – 提供最優質的資源集合!
正文完