Python实现的矩阵加法示例 - 使用自定义类MyMatrix class MyMatrix: def __init__(self, l1, l2, l3): # 初始化函数,用于创建MyMatrix对象 # 参数:l1, l2, l3 - 三个列表 # 返回:无 self.l = [l1.copy(), l2.copy(), l3.copy()] def __str__(self): # 字符串表示方法,用于返回MyMatrix对象的字符串表示 # 参数:无 # 返回:包含矩阵内容的字符串 s = [] for i in range(len(self.l)): s.append('| ' + ' '.join([str(x) for x in self.l[i]]) + ' |') return '\n'.join(s) def __add__(self, other): # 加法重载方法,用于实现矩阵的加法 # 参数:other - 另一个MyMatrix对象 # 返回:新的MyMatrix对象,表示两个矩阵相加的结果 m3 = MyMatrix(self.l[0], self.l[1], self.l[2]) length = min(len(self.l), len(other.l)) height = min(len(self.l[0]), len(other.l[0])) for i in range(length): for j in range(height): m3.l[i][j] += other.l[i][j] return m3 m1 = MyMatrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) m2 = MyMatrix([10, 20, 30], [40, 50, 60], [70, 80, 90]) print(m1, end='\n\n') print(m2, end='\n\n') print(m1 + m2, end='\n\n') print(m1, end='\n\n')
运行结果:
发表评论