列表列表(List of Lists)
使用嵌套列表来表示矩阵,其中每个内部列表代表矩阵的一行。
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
NumPy数组
使用NumPy库的`ndarray`对象来表示多维数组,包括矩阵。
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
文件读取
通过读取文件来构建矩阵,例如从文本文件中读取数据。
dataSet = []
with open('testSet.txt', 'r') as fileIn:
for line in fileIn.readlines():
temp = []
lineArr = line.strip().split('\t')
temp.append(float(lineArr))
temp.append(float(lineArr))
dataSet.append(temp)
以上是Python中表示矩阵的一些常见方法。您可以根据具体需求选择合适的方法来表示和使用矩阵