Python 关于矩阵类函数的问题

Python 关于矩阵类函数的问题,python,Python,首先,这是我的代码: class matrix: def __init__(self, m, n): self._m, self._n = m, n L = [] # We first define our pre-matrix as an empty list for i in range(m): L.append(0) for j in range(m): L[j] = [0] * n self._ma

首先,这是我的代码:

class matrix:
def __init__(self, m, n): 
    self._m, self._n = m, n

    L = []  # We first define our pre-matrix as an empty list
    for i in range(m):  
        L.append(0)

    for j in range(m):  
        L[j] = [0] * n

    self._matrix = L 


def __setitem__(self, c, value):
    self._matrix[c[0] - 1][c[1] - 1] = value

def __str__(self):
    l = ""  
    for i in range(self._m):
        l = l + " "  
        for j in range(self._n):
            l = l + str(self._matrix[i][j]) + " "  
        l = l + " \n"  
    return l


def __add__(self, other):
    result = [[self._matrix[i][j] + other._matrix[i][j] for j in range(len(self._matrix[0]))] for i in range(len(self._matrix))]
    return result
当添加两个(非零)矩阵时,我无法像我的
\uuuu str\uuuu
方法那样很好地打印结果,而不是

a b c 
d e f
我和往常一样

[[a, b, c],[d, e, f]]

有人知道如何解决这个问题吗?

add函数的返回类型是一个
列表。它应该是一个
矩阵

def __add__(self, other):
    result = matrix(self._m, self._n)
    result._matrix = [[self._matrix[i][j] + other._matrix[i][j] for j in range(len(self._matrix[0]))] for i in range(len(self._matrix))]
    return result 

因为您的
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu!