首页 > 解决方案 > python-igraph如何添加带有权重的边?

问题描述

python-igraph如何添加带有权重的边?

我有一个像[('1', '177', 1.0), ('1', '54', 1.0), ('1', '61', 2.0), ('1', '86', 2.0), ('10', '100', 38.0)]. 元组中的最后一个是边从'1'到的权重'177'。但是怎么添加呢?我用

g.add_vertices(vertexList)
g.add_edges(edgelist)

但这是错误的。

标签: pythonigraph

解决方案


We need to do some pre-processing first.

The following code works fine and does what you asked.


from igraph import *

# Here we have 5 edges
a = [('1', '177', 1.0), ('1', '54', 1.0), ('1', '61', 2.0), 
     ('1', '86', 2.0), ('10', '100', 38.0)]    

edge = []
weights = []
# the loop for i is in range(5) because you have 5 edges
for i in range(5):
    for j in range(2):
        k =2
        edge.append(a[i][j])
    weights.append(a[i][k])

edges = [(i,j) for i,j in zip(edge[::2], edge[1::2])]

list1 = []
for i in range(len(edges)):
    list1.append((int(edges[i][0]), int(edges[i][1])))

g= Graph()
g.add_vertices(178)
g.add_edges(list1)
g.es['weight'] = weights

g.ecount()
5

g.es['weight']
[1.0, 1.0, 2.0, 2.0, 38.0]

推荐阅读