【发布时间】: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]])
【问题讨论】: