Более простой и понятный способ - просто использовать словарь с отсортированными кортежами в качестве ключей. Кортежи соответствуют вашему матричному индексу. Переопределите __getitem__
и __setitem__
для доступа к словарю по отсортированным кортежам; Вот пример класса:
class Matrix(dict):
def __getitem__(self, index):
return super(Matrix, self).__getitem__(tuple(sorted(index)))
def __setitem__(self, index, value):
return super(Matrix, self).__setitem__(tuple(sorted(index)), value)
А затем используйте это так:
>>> matrix = Matrix()
>>> matrix[2,3] = 1066
>>> print matrix
{(2, 3): 1066}
>>> matrix[2,3]
1066
>>> matrix[3,2]
1066
>>> matrix[1,1]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "z.py", line 3, in __getitem__
return super(Matrix, self).__getitem__(tuple(sorted(index)))
KeyError: (1, 1)