Vector向量是之前文章中已经实现的向量类
from playLA.Vector import Vector
class Matrix(object):
def __init__(self, list2d):
"""初始化矩阵类"""
self._values = [row[:] for row in list2d]
def row_vector(self, index):
"""返回矩阵的第index个行向量"""
return Vector(self._values[index])
def col_vector(self, index):
"""返回矩阵的第index个列向量"""
return Vector([row[index] for row in self._values])
def __getitem__(self, pos):
"""返回矩阵pos位置的元素"""
r, c = pos
return self._values[r][c]
def size(self):
"""返回矩阵中的元素的个数"""
r, c = self.shape()
return r * c
def shape(self):
"""返回矩阵的形状:(行数, 列数)"""
return len(self._values), len(self._values[0])
def row_num(self):
"""返回矩阵的行数"""
return self.shape()[0]
__len__ = row_num
def col_num(self):
"""返回矩阵的列数"""
return self.shape()[1]
def __repr__(self):
return "Matrix({})".format(self._values)
__str__ = __repr__
if __name__ == '__main__':
matrix = Matrix([[1, 2], [3, 4]])
print(matrix)
print("matrix.shape = {}".format(matrix.shape()))
print("matrix.size = {}".format(matrix.size()))
print("len(matrix) = {}".format(len(matrix)))
print("matrix[0][0] = {}".format(matrix[0, 0]))
网友评论