[英]Partition edges of a graph with NetworkX and Python
I would like to partition edges of a graph g
based on edge attributes, using Python and NetworkX.我想使用 Python 和 NetworkX 根据边缘属性对图g
的边缘进行分区。 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
.我想根据cat
属性将图g
划分为图ga
和gb
并保留节点属性pos
。 Note that nodes 1
and 4
will belong to both ga
and gb
.请注意,节点1
和4
将同时属于ga
和gb
。 Is there a library support for this operation?这个操作有库支持吗?
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']))
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.