检查是否存在稀疏矩阵条目 [英] Check if scipy sparse matrix entry exists
本文介绍了检查是否存在稀疏矩阵条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用
S = scipy.sparse.lil_matrix((n,n),dtype=int)
按预期,print S
不显示任何内容,因为未分配任何内容.
但是如果我测试:
As expected print S
doesn't show anything, since nothing has been assigned.
Yet if I test:
print S[0,0]==0
我收到true
.
是否可以测试以前是否设置了值?例如.按照ifempty
的说法?
Is there a way to test if a value has been set before? E.g. along the lines of ifempty
?
推荐答案
您可以使用
def get_items(s):
s_coo = s.tocoo()
return set(zip(s_coo.row, s_coo.col))
演示:
>>> n = 100
>>> s = scipy.sparse.lil_matrix((n,n),dtype=int)
>>> s[10, 12] = 1
>>> (10, 12) in get_items(s)
True
请注意,对于其他类型的稀疏矩阵,可以明确设置0:
Note that for other types of sparse matrices, 0 can be expicetely set:
>>> s = scipy.sparse.csr_matrix((n,n),dtype=int)
>>> s[12, 14] = 0
>>> (12, 14) in get_items(s)
True
这篇关于检查是否存在稀疏矩阵条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文