【发布时间】:2016-12-13 16:33:31
【问题描述】:
例如,我有一个文本文件,其中每条线表示图上的一条边
2 5 1
表示节点 2 和 5 之间的权重为 1 的边。我想使用这些元组创建一个稀疏邻接矩阵。通常,我会将稀疏矩阵初始化为
G = scipy.sparse.lil_matrix((n,n))
其中 n 是图中的节点数。但在这种情况下,我不知道“n”是什么。有没有比遍历文件的行以找到最大节点索引、创建 lil_matrix 然后再次遍历文件更有效的方法来创建矩阵?我目前的实现是这样的:
n = 0
with open(gfile) as f:
for line in f:
temp = map(int,line.split())
n = np.max([n,temp[0],temp[1]])
G = sp.lil_matrix((n,n))
with open(gfile) as f:
for line in f:
temp = map(int,line.split())
G[temp[0],temp[1]] = temp[2]
【问题讨论】:
标签: python numpy scipy sparse-matrix