Python 如何在字典中的igraph对象中添加边
我用字典来表示一组边。我用字典的键来表示边,用值来表示权重。字典当前看起来如下所示:Python 如何在字典中的igraph对象中添加边,python,time-complexity,igraph,edges,Python,Time Complexity,Igraph,Edges,我用字典来表示一组边。我用字典的键来表示边,用值来表示权重。字典当前看起来如下所示: {(0, 1): 2, (1, 2): 6, (0, 2): 3} 我试试这个: edges, weights = [], [] for edge, weight in dict_edges.items(): edges += [edge] weights.append(weight) g.add_edges(edges) g.es["weight"] = weights 但是,我不知道是
{(0, 1): 2, (1, 2): 6, (0, 2): 3}
我试试这个:
edges, weights = [], []
for edge, weight in dict_edges.items():
edges += [edge]
weights.append(weight)
g.add_edges(edges)
g.es["weight"] = weights
但是,我不知道是否有更快或更干净的方法来做到这一点
有人对如何改进我的新产品有什么建议吗?你做的很好;也许可以用
zip
调用替换for
循环。如果您使用的是Python 2.x::
from itertools import izip
edges, weights = izip(*dict_edges.iteritems())
g = Graph(edges, edge_attrs={"weight": weights})
如果您使用的是Python 3.x::
edges, weights = zip(*dict_edges.items())
g = Graph(edges, edge_attrs={"weight": weights})