【问题标题】:Transposing matrix twice using classes without numpy使用没有 numpy 的类转置矩阵两次
【发布时间】:2021-12-15 12:58:45
【问题描述】:

我需要实现一个方法 transpose(),它返回一个已经转置的新矩阵。它还必须打印出该矩阵的字符串。它在使用 matrix.transpose() 时有效,但在使用 matrix.transpose().transpose() 时无效,因为 transpose() 返回一个字符串。 我不能使用 numpy 或向方法添加更多输入。我该怎么办?

from copy import deepcopy


class Matrix:
    def __init__(self, rows):
        self.rows = rows[:]
    def transpose(self):
            copy = deepcopy(self.rows)
            transposed = [[copy[j][i] for j in range(len(copy))] for i in range(len(copy[0]))]

        matrix = ''
        for element in transposed:
            for i in element:
                matrix += '%2d' % ((i))
                matrix += ' '
            matrix = matrix[:-1]
            matrix += '\n'


       return matrix

a = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

【问题讨论】:

    标签: python matrix


    【解决方案1】:

    您可以在transpose 中创建一个新的Matrix 对象,并在打印其内容后将其返回。 为方便起见,我将您的打印代码移至将矩阵转换为字符串的方法(请注意,名为 __repr__ 的方法将被 print 隐式调用)。 代码:

    from copy import deepcopy
    
    class Matrix:
         def __init__(self, rows):
             self.rows = rows[:]
    
         def transpose(self):
             copy = deepcopy(self.rows)
             transposed = [[copy[j][i] for j in range(len(copy))] for i in range(len(copy[0]))]
             transposed_matrix = Matrix(transposed)
             print(transposed_matrix)
             return transposed_matrix
    
         def __repr__(self):
             matrix = ''
             for element in self.rows:
                 for i in element:
                     matrix += '%2d' % ((i))
                     matrix += ' '
                 matrix = matrix[:-1]
                 matrix += '\n'
             return matrix
    

    其他改进:

    • transpose 中可以将矩阵转置更改为transposed = list(map(list, zip(*self.rows)))
    • 使用格式字符串代替'%2d' % ((i)) -> f'{i:2}'
    • join 对格式化矩阵很有帮助: return '\n'.join(' '.join(f'{i:2}' for i in row) for row in self.rows)

    现在完整的代码如下所示

    class Matrix:
         def __init__(self, rows):
             self.rows = rows[:]
    
         def transpose(self):
             transposed = list(map(list, zip(*self.rows)))
             transposed_matrix = Matrix(transposed)
             print(transposed_matrix)
             return transposed_matrix
    
         def __repr__(self):
             return '\n'.join(' '.join(f'{i:2}' for i in row) for row in self.rows)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多