The simplest approach would just be to use nested lists:
>>> matrix = [[0] * num_cols] * num_rows
>>> matrix[i][j] = 'value' # row i, column j, value 'value'
>>> print repr(matrix[i][j])
'value'
Alternatively, if you’re going to be dealing with sparse matrices (i.e. matrices with a lot of empty or zero values), it might be more efficient to use nested dictionaries. In this case, you could implement setter and getter functions which will operate on a matrix, like so:
def get_element(mat, i, j, default=None):
# This will also set the accessed row to a dictionary.
row = mat.setdefault(i, {})
return row.setdefault(j, default)
def set_element(mat, i, j, value):
row = mat.setdefault(i, {})
row[j] = value
And then you would use them like this:
>>> matrix = {}
>>> set_element(matrix, 2, 3, 'value') # row 2, column 3, value 'value'
>>> print matrix
{2: {3: 'value'}}
>>> print repr(get_element(matrix, 2, 3))
'value'
If you wanted, you could implement a Matrix
class which implemented these methods, but that might be overkill:
class Matrix(object):
def __init__(self, initmat=None, default=0):
if initmat is None: initmat = {}
self._mat = initmat
self._default = default
def __getitem__(self, pos):
i, j = pos
return self._mat.setdefault(i, {}).setdefault(j, self._default)
def __setitem__(self, pos, value):
i, j = pos
self._mat.setdefault(i, {})[j] = value
def __repr__(self):
return 'Matrix(%r, %r)' % (self._mat, self._default)
>>> m = Matrix()
>>> m[2,3] = 'value'
>>> print m[2,3]
'value'
>>> m
Matrix({2: {3: 'value'}}, 0)