python - 使用 igraph 从字典填充图形

标签 python igraph

我有一本字典,其中包含关注者-关注者信息。例如:

a --> b,c,d
b --> c,d
c --> d

这里的意思是,a跟随b,c,d。 b 跟随 c、d。 c 之后是 d。我有以下相应的字典:

{'a': ['b', 'c', 'd'], 'b': ['c', 'd'], 'c': ['d']}

我想根据 igraph 中的字典创建一个有向图.

我目前正在做的是:

import igraph

d = {'a': ['b', 'c', 'd'], 'b': ['c', 'd'], 'c': ['d']}

edges = []
vertices_set = set()
for key in d:
    vertices_set.add( key )
    for item in d[key]:
        edges.append( (key, item) )
        vertices_set.add( item )

# vertices_set: set(['a', 'c', 'b', 'd'])
# edges: [('a', 'b'), ('a', 'c'), ('a', 'd'), ('c', 'd'), ('b', 'c'), ('b', 'd')]

g = igraph.Graph( directed=True )
g.add_vertices( len(vertices_set) )
g.vs['name'] = list(vertices_set)
g.add_edges( edges )

print(len(g.vs))
print(len(g.es))

这段代码按预期工作。然而,如您所见,它相当丑陋(而且很可能比应有的速度慢)。

我觉得,应该有一种更快和/或更Pythonic的方式来做到这一点。有意见吗?

最佳答案

您可以使用Graph.TupleList功能:

>>> from igraph import Graph
>>> d = {'a': ['b', 'c', 'd'], 'b': ['c', 'd'], 'c': ['d']}
>>> g = Graph.TupleList([(k, v) for k, vs in d.iteritems() for v in vs])
>>> print g
IGRAPH UN-- 4 6 --
+ attr: name (v)
+ edges (vertex names):
a -- b, c, d   b -- a, c, d   c -- a, b, d   d -- a, b, c

关于python - 使用 igraph 从字典填充图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34571534/

相关文章:

删除无边的自环和顶点

r - 如何在 R 中的多个模拟图形上应用一个函数

python - Django REST Framework 中的自定义列表权限

python - Qt4 : Write a function that creates a dialog and returns the choice of the user

python - 在 MayaVi 中指定 3D 点的绝对颜色

python - 在Python中将元组转换为字典

Windows 上的 Python 子进程问题

python - 从 std :vector in Cython 中删除一个元素

R 没有在layout_with_sugiyama 中采用参数hgap

r - 计算最小 s-t 切割尚未在 igraph 中实现