python中构建稀疏矩阵主要基于scipy的coo_matrix, csr_matrix。csr_matrix存储密度更大,但是不容易手工构建。一般先基于coo_matrix构建稀疏矩阵,然后通过tocsr()转换成csr_matrix
>>> import numpy as np
>>> row = np.array([0, 3, 1, 0])
>>> col = np.array([0, 3, 1, 2])
>>> data = np.array([4,5,7,8])
>>> import scipy.sparse
>>> from scipy.sparse import coo_matrix, csr_matrix
>>> d1 = coo_matrix((data, (row, col)))
>>> d1.toarray()
array([[4, 0, 8, 0],
[0, 7, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 5]])
>>>