Python 使用类打印列表中的项目,该项目是列表,打印时看起来像一个数组

Python 使用类打印列表中的项目,该项目是列表,打印时看起来像一个数组,python,class,matrix,arraylist,printing,Python,Class,Matrix,Arraylist,Printing,所以我知道标题的描述有点混乱,但希望用图片解释它可能更容易理解。所以基本上我有一个叫做“矩阵”的类: 因此,当我在类矩阵中调用方法set_matrix时,以下代码应将m1返回为: 我已经用逗号分隔的数字做过了,但我不知道用数字做 列表中用空格分隔:/。任何帮助都将不胜感激:) 这是以下代码,每个列表的项目用逗号分隔: class Matrix: def __init__(self): self.__list = [] def set_matrix(self, matrix_li

所以我知道标题的描述有点混乱,但希望用图片解释它可能更容易理解。所以基本上我有一个叫做“矩阵”的类:

因此,当我在类矩阵中调用方法set_matrix时,以下代码应将m1返回为:

我已经用逗号分隔的数字做过了,但我不知道用数字做 列表中用空格分隔:/。任何帮助都将不胜感激:)

这是以下代码,每个列表的项目用逗号分隔:

class Matrix:

def __init__(self):

    self.__list = []

def set_matrix(self, matrix_list):

    self.__list.append(matrix_list)

def __str__(self):

    output_string = ''

    for i in self.__list:

        for j in i:
            
            output_string += str(j) + '\n'

    return output_string

m1 = Matrix()

m1.set_matrix( [[1,2,3,4],[5,6,7,8],[9,8,7,6]] )
print('m1:')
print(m1)
找到解决方案:

class Matrix:

def __init__(self):

    self.__list = []

def set_matrix(self, matrix_list):

    self.__list.append(matrix_list)

def __str__(self):

    output_string = ''

    for i in self.__list:

        for j in i:
            
            output_string += str(j).replace(',', '').replace('[', '[ ').replace(']', ' ]') + '\n'

    return output_string

m1 = Matrix()

m1.set_matrix( [[1,2,3,4],[5,6,7,8],[9,8,7,6]] )
print('m1:')
print(m1)