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)

 

 

 

 

 

posted on 2012-08-07 15:59  grep  阅读(3483)  评论(0)    收藏  举报