简体   繁体   English

字典中的稀疏矩阵

[英]sparse matrix from dictionaries

I just started to learn to program in Python and I am trying to construct a sparse matrix using Scipy package.我刚开始学习在 Python 中编程,我正在尝试使用 Scipy package 构造一个稀疏矩阵。 I found that there are different types of sparse matrices, but all of them require to store using three vectors like row, col, data;我发现有不同类型的稀疏矩阵,但它们都需要使用行、列、数据等三个向量来存储; or if you want to each new entry separately, like S(i,j) = s_ij you need to initiate the matrix with a given size.或者,如果您想分别输入每个新条目,例如 S(i,j) = s_ij,您需要以给定的大小启动矩阵。
My question is if there is a way to store the matrix entrywise without needing the initial size, like a dictionary.我的问题是,是否有一种方法可以在不需要初始大小的情况下逐项存储矩阵,例如字典。

You can use usual dictionary with tuples of two integers as indices.您可以使用带有两个整数的元组作为索引的常用字典。 For example:例如:

matrix = {}
matrix[5, 7] = 1
matrix[3, 8] = 5

No. Any matrix in Scipy, sparse or not, must be instantiated with a size.不可以。Scipy 中的任何矩阵,无论是否稀疏,都必须使用大小进行实例化。

dic={}
a,b=int(input("Enter the order:")),int(input())
for i in range(a):
    for j in range(b):
        c=int(input())
        if c!=0:
            dic[(i,j)]=c
if len(dic)<=(a+b)/2:
    print("sparse metrix")
else:
    print("non sparse metrix")

for i in range(a):
    for j in range(b):
        print(dic.get((i,j),0),end=" ")
    print()    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM