Python OOP __Add__ 矩阵在一起(循环问题)

标签 python oop class matrix addition

class Matrix:
  def __init__(self, data):
    self.data = data

  def __repr__(self):
    return repr(self.data)  

  def __add__(self, other):
    data = []

    for j in range(len(self.data)):
        for k in range(len(self.data[0])):
            data.append([self.data[k] + other.data[k]])
        data.append([self.data[j] + other.data[j]])
        data = []

    return Matrix(data)  

x = Matrix([[1,2,3],[2,3,4]])
y = Matrix([[10,10,10],[10,10,10]])
print(x + y,x + x + y)

我能够让矩阵添加 1 行 n 列,但是当我试图通过添加第二个循环来改进所有 n 乘 n 矩阵时,我遇到了这个错误。

Traceback (most recent call last):

  line 24, in <module>
    print(x + y,x + x + y)

  line 15, in __add__
    data.append([self.data[k] + other.data[k]])

IndexError: list index out of range

最佳答案

这个怎么样:

class Matrix:
  def __init__(self, data):
    self.data = data

  def __repr__(self):
    return repr(self.data)  

  def __add__(self, other):
    data = []

    for j in range(len(self.data)):
        data.append([])
        for k in range(len(self.data[0])):
            data[j].append(self.data[j][k] + other.data[j][k])

    return Matrix(data)

关于Python OOP __Add__ 矩阵在一起(循环问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5328684/

相关文章:

python - 绘制 2 度线性回归的困难

python - ValueError : The truth value of a Series is ambiguous. 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all():返回具有空值的列

c++ - 减少重复的方法?

c# - 为什么我需要单例设计模式?

Java 动态绑定(bind)失败

python - 如何制作这些连续直方图/密度估计图

python - pyQt - 如何基于 QGroupBox 选择小部件

javascript - 将带参数的方法添加到 javascript 对象

javascript - 具有 Set 集合的类方法不返回任何内容

c++ - 是矩形 A = 矩形(3, 4);相当于矩形 A(3,4);?