如何在 Python 中从字典创建 igraph 对象

发布于 2024-10-29 13:09:01 字数 348 浏览 6 评论 0原文

我在 Python 程序中使用字典来表示图形。我使用字典的键来表示顶点,使用值来表示每个顶点的相邻节点。字典目前看起来像这样:

{  
   'v1' : ['v2','v3'],
   'v2' : ['v1'],
   'v3' : ['v1','v4'],
   'v4' : ['v3']
    // And so on. 
}

是否有一种简单的方法来创建新的 igraph 对象 来自这本词典?如果没有简单的方法,那么下一个最佳选择是什么?

I'm using a dictionary to represent a graph in my Python program. I'm using the keys of the dictionary to represent vertices and the values to represent the adjacent nodes of each vertex. The dictionary currently looks like this:

{  
   'v1' : ['v2','v3'],
   'v2' : ['v1'],
   'v3' : ['v1','v4'],
   'v4' : ['v3']
    // And so on. 
}

Is there a straightforward way to create a new igraph object from this dictionary? If there's no easy way, what's the next-best option?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧时光的容颜 2024-11-05 13:09:01

好吧,根据 docs,似乎 igraph 期望将顶点编码为整数。因此,您需要指定从顶点整数映射,然后您实际上可以像这样继续操作:

G= {'v1': ['v2', 'v3'], 'v2': ['v1'], 'v3': ['v1', 'v4'], 'v4': ['v3']}
mvi= {'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4}
graph= igraph.Graph(edges= [(mvi[v], mvi[a]) for v in G.keys() for a in G[v]])

Well, according to the docs, it seems that igraph expects vertices encoded as integers. So you need to specify a mapping from your vertices to integers and then you could actually proceed for example like this:

G= {'v1': ['v2', 'v3'], 'v2': ['v1'], 'v3': ['v1', 'v4'], 'v4': ['v3']}
mvi= {'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4}
graph= igraph.Graph(edges= [(mvi[v], mvi[a]) for v in G.keys() for a in G[v]])
望她远 2024-11-05 13:09:01

我做了类似的事情,也将顶点名称导入到图中:

relations = {'v1': ['v2','v3'], 'v2': ['v1'], 'v3': ['v1','v4']}
g = igraph.Graph()
g.add_vertices(list(set(list(relations.keys()) + list([a for v in relations.values() for a in v]))))
g.add_edges([(v, a) for v in relations.keys() for a in relations[v]])

I did something like this which imports names of vertices to the graph also:

relations = {'v1': ['v2','v3'], 'v2': ['v1'], 'v3': ['v1','v4']}
g = igraph.Graph()
g.add_vertices(list(set(list(relations.keys()) + list([a for v in relations.values() for a in v]))))
g.add_edges([(v, a) for v in relations.keys() for a in relations[v]])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文