In [74]: from scipy import sparse
In [75]: M = sparse.csr_matrix([[0,0,1,0,0,-1,0,3,0,-6,4],
...: [-1,0,4,0,0,0,0,0,0,0,-2]])
In [76]: M
Out[76]:
<2x11 sparse matrix of type '<class 'numpy.int64'>'
with 8 stored elements in Compressed Sparse Row format>
In [77]: M.A
Out[77]:
array([[ 0, 0, 1, 0, 0, -1, 0, 3, 0, -6, 4],
[-1, 0, 4, 0, 0, 0, 0, 0, 0, 0, -2]], dtype=int64)
lil
格式按行给出数据:
In [78]: Ml = M.tolil()
In [79]: Ml.data
Out[79]: array([list([1, -1, 3, -6, 4]), list([-1, 4, -2])], dtype=object)
现在只需要按照您想要的方式将这些列表写入文件:
In [81]: from itertools import zip_longest
In [82]: for i,j in zip_longest(*Ml.data, fillvalue=''):
...: astr = '%s, %s'%(i,j)
...: print(astr)
...:
1, -1
-1, 4
3, -2
-6,
4,
zip_longest
使用最长的作为引用,是遍历多个列表的简单方法。