[英]python-igraph how to add edges with weight?
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)
但這是錯誤的。
我們需要先進行一些預處理 。
以下代碼可以正常運行,並且可以完成您所要求的操作。
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]
您不再需要“預處理”數據,因為這種格式對於新方法是准確的:
g = Graph.TupleList([(from, to, weight], ...)
作者的另一個示例:
g=Graph.TupleList([("a", "b", 3.0), ("c", "d", 4.0), ("a", "c", 5.0)], weights=True)
該方法可從0.6.1版本開始使用,作者在這里說: https : //answers.launchpad.net/igraph/+question/206397
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.