【问题标题】:Using a class to print items of a list which the item is a list, looking like an array when printed [duplicate]使用一个类来打印列表中的项目,该项目是一个列表,打印时看起来像一个数组[重复]
【发布时间】:2021-06-26 15:38:35
【问题描述】:

所以我知道标题的描述有点令人困惑,但希望用图片来解释它可能更容易理解。所以基本上我有一个名为'Matrix'的类:

所以当我在类 Matrix 中调用 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)

【问题讨论】:

    标签: python class matrix arraylist printing


    【解决方案1】:

    找到解决方案:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      • 2022-08-08
      • 1970-01-01
      • 2017-09-24
      相关资源
      最近更新 更多