使用 NetworkX 和 Python 对图的边进行分区

发布于 2025-01-15 14:44:00 字数 529 浏览 2 评论 0原文

我想使用 Python 和 NetworkX 根据边缘属性对图 g 的边缘进行分区。在此代码片段中:

import networkx as nx

g = nx.Graph()
g.add_node(1, pos=[0, 0])
g.add_node(2, pos=[0, 2])
g.add_node(3, pos=[1, 1])
g.add_node(4, pos=[2, 1])
g.add_edge(1, 3, cat='a')
g.add_edge(4, 3, cat='a')
g.add_edge(1, 2, cat='b')
g.add_edge(4, 2, cat='b')

我想根据 cat 属性将图 g 划分为图 gagb 并保留节点属性pos。请注意,节点 14 将同时属于 gagb。有库支持此操作吗?

I would like to partition edges of a graph g based on edge attributes, using Python and NetworkX. In this snippet:

import networkx as nx

g = nx.Graph()
g.add_node(1, pos=[0, 0])
g.add_node(2, pos=[0, 2])
g.add_node(3, pos=[1, 1])
g.add_node(4, pos=[2, 1])
g.add_edge(1, 3, cat='a')
g.add_edge(4, 3, cat='a')
g.add_edge(1, 2, cat='b')
g.add_edge(4, 2, cat='b')

I would like to partition graph g into graphs ga and gb based on cat attribute and retain node attribute pos. Note that nodes 1 and 4 will belong to both ga and gb. Is there a library support for this operation?

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

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

发布评论

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

评论(2

月下凄凉 2025-01-22 14:44:00

您可以使用列表理解和集合的组合:

ga = g.subgraph(set(*[[u,v] for (u,v,data) in g.edges(data=True) if data.get('cat')=='a']))
gb = g.subgraph(set(*[[u,v] for (u,v,data) in g.edges(data=True) if data.get('cat')=='b']))

you could use a combination of list comprehension and sets:

ga = g.subgraph(set(*[[u,v] for (u,v,data) in g.edges(data=True) if data.get('cat')=='a']))
gb = g.subgraph(set(*[[u,v] for (u,v,data) in g.edges(data=True) if data.get('cat')=='b']))
不一样的天空 2025-01-22 14:44:00

这似乎是一个简单的解决方案:

ga = g.edge_subgraph(e for e in g.edges() if g.edges[e]['cat']=='a')
gb = g.edge_subgraph(e for e in g.edges() if g.edges[e]['cat']=='b')

This seems to be a simple solution:

ga = g.edge_subgraph(e for e in g.edges() if g.edges[e]['cat']=='a')
gb = g.edge_subgraph(e for e in g.edges() if g.edges[e]['cat']=='b')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文