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)

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM