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