简体   繁体   English

python-igraph如何添加带重量的边缘?

[英]python-igraph how to add edges with weight?

python-igraph how to add edges with weight? python-igraph如何添加带重量的边缘?

I have a tuple list like [('1', '177', 1.0), ('1', '54', 1.0), ('1', '61', 2.0), ('1', '86', 2.0), ('10', '100', 38.0)] . 我有一个元组列表,例如[('1', '177', 1.0), ('1', '54', 1.0), ('1', '61', 2.0), ('1', '86', 2.0), ('10', '100', 38.0)] The last one in the tuple is the weight of edge from '1' to '177' . 元组中的最后一个是从'1''177'的边的权重。 But how to add it? 但是如何添加呢? I use 我用

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

but it is wrong. 但这是错误的。

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]

You have not longer "preprocess" data, becouse this format is accurate for new method: 您不再需要“预处理”数据,因为这种格式对于新方法是准确的:

g = Graph.TupleList([(from, to, weight], ...)

one more example from author: 作者的另一个示例:

g=Graph.TupleList([("a", "b", 3.0), ("c", "d", 4.0), ("a", "c", 5.0)], weights=True)

Method is available from version 0.6.1, what said author here: https://answers.launchpad.net/igraph/+question/206397 该方法可从0.6.1版本开始使用,作者在这里说: https : //answers.launchpad.net/igraph/+question/206397

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

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