これはやり過ぎかもしれませんが、次の Matrix クラスはそれ自体の表現を自動的に作成できます。
class Matrix:
def __init__(self, rows, columns):
self.__data = tuple([None] * columns for row in range(rows))
self.__rows, self.__columns = rows, columns
def __repr__(self):
table = Matrix(self.rows, self.columns)
rows, columns = [0] * self.rows, [0] * self.columns
for (row, column), value in self:
lines = tuple(repr(value).replace('\r\n', '\n')
.replace('\r', '\n').split('\n'))
table[row, column] = self.__yield(lines)
rows[row] = max(rows[row], len(lines))
columns[column] = max(columns[column], max(map(len, lines)))
return ('\n' + '+'.join('-' * column for column in columns) + '\n') \
.join('\n'.join('|'.join(next(table[row, column])
.ljust(columns[column]) for column in range(table.columns))
for line in range(rows[row])) for row in range(table.rows))
def __len__(self):
return self.rows * self.columns
def __getitem__(self, key):
row, column = key
return self.__data[row][column]
def __setitem__(self, key, value):
row, column = key
self.__data[row][column] = value
def __delitem__(self, key):
self[key] = None
def __iter__(self):
for row in range(self.rows):
for column in range(self.columns):
key = row, column
yield key, self[key]
def __reversed__(self):
for row in range(self.rows - 1, -1, -1):
for column in range(self.columns - 1, -1, -1):
key = row, column
yield key, self[key]
def __contains__(self, item):
for row in self.__data:
if item in row:
return True
return False
def freeze(self):
self.__data = tuple(map(tuple, self.__data))
def thaw(self):
self.__data = tuple(map(list, self.__data))
@property
def rows(self):
return self.__rows
@property
def columns(self):
return self.__columns
@staticmethod
def __yield(lines):
for line in lines:
yield line
while True:
yield ''
行列を設定、加算、または乗算する方法が必要な場合は、これらの関数が操作の補足として機能します。
def set_matrix(matrix, array):
for y, row in enumerate(array):
for x, item in enumerate(row):
matrix[y, x] = item
def add_matrix(a, b):
assert a.rows == b.rows and a.columns == b.columns
c = Matrix(a.rows, a.columns)
for key, _ in c:
c[key] = a[key] + b[key]
return c
def mul_matrix(a, b):
assert a.columns == b.rows
c = Matrix(a.rows, b.columns)
for key, _ in c:
row, column = key
c[key] = sum(j * k for j, k in
zip((a[row, i] for i in range(a.columns)),
(b[i, column] for i in range(b.rows))))
return c