matrix in python
A fairly standard way to represent such a matrix is by means of a list of lists. like this.
matrix = [[3, 0, -2, 11], [0, 9, 0, 0], [0, 7, 0, 0], [0, 0, 0, -5]]
then access by
element = matrix[rownum][colnum]
but for sparse matrices.
It's simple to implement sparse matrices using dictionaries with tuple indices.
matrix = {(0, 0): 3, (0, 2): -2, (0, 3): 11,
(1, 1): 9, (2, 1): 7, (3, 3): -5}
then access by
if (rownum, colnum) in matrix: element = matrix[(rownum, colnum)] else: element = 0
or by dictionary get method
element = matrix.get((rownum, colnum), 0)
浙公网安备 33010602011771号