简体   繁体   English

如何从字典中添加igraph对象中的边

[英]How to add edges in an igraph object from a dictionary

I'm using a dictionary to represent a set of edges. 我正在使用字典来表示一组边。 I'm using the keys of the dictionary to represent edges and the values to represent the weights. 我正在使用字典的键来表示边缘,并使用值来表示权重。 The dictionary currently looks like this: 字典目前看起来像这样:

{(0, 1): 2, (1, 2): 6, (0, 2): 3}

I try this: 我试试这个:

edges, weights = [], []
for edge, weight in dict_edges.items():
    edges += [edge]
    weights.append(weight)

g.add_edges(edges)
g.es["weight"] = weights

But, I don't if there is a faster way or more cleaner to do this. 但是,如果有更快的方式或更清洁,我不会这样做。

Anyone have any suggestions how to improve my new? 任何人有任何建议如何改善我的新?

What you do is perfectly fine; 你做的很完美; maybe the for loop could be replaced with a zip call. 也许for循环可以用zip调用替换。 If you are using Python 2.x:: 如果您使用的是Python 2.x ::

from itertools import izip
edges, weights = izip(*dict_edges.iteritems())
g = Graph(edges, edge_attrs={"weight": weights})

If you are using Python 3.x:: 如果您使用的是Python 3.x ::

edges, weights = zip(*dict_edges.items())
g = Graph(edges, edge_attrs={"weight": weights})

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

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