Skip to main content
 首页 » 编程设计

python之检查 scipy 稀疏矩阵条目是否存在

2025年05月04日9Terrylee

我使用

初始化一个空的稀疏矩阵
S = scipy.sparse.lil_matrix((n,n),dtype=int) 

正如预期的那样,print S 没有显示任何内容,因为尚未分配任何内容。 然而,如果我测试:

print S[0,0]==0 

我收到 true。

有没有办法测试之前是否设置过值?例如。按照 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:

>>> s = scipy.sparse.csr_matrix((n,n),dtype=int) 
>>> s[12, 14] = 0 
>>> (12, 14) in get_items(s) 
True