Skip to main content
 首页 » 编程设计

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

2025年05月04日11wayfarer

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)