[英]Is there a way to add single nodes/edges in JSON format to networkx graph?
[英]Efficient way to replace nodes in a networkx graph with follow-through edges
我正在尝试用后续边替换图中的节点。 这意味着被替换/删除节点的每个前驱节点都将连接到被替换/删除节点的每个后继节点。
例如,考虑一个具有 5 个节点的路径图,其中边为(0, 1), (1, 2), (2, 3), (3, 4)
,我希望用后续边替换节点 1 和 3 ( (0,2)
为节点 1) 和 ( (2,4)
为节点 3)。 最终的图应该有边(0, 2), (2, 4)
。
Networkx 没有内置函数/算法,所以你应该手动完成。 Itertools模块将帮助您自动化边缘的构建以创建:
import itertools as it
import networkx as nx
G = nx.DiGraph()
G.add_edges_from([
(1,2),
(2,3),
(3,5),
(4,5),
(5,6),
(5,7)
])
nodes_to_delete = [2, 5]
for node in nodes_to_delete:
G.add_edges_from(
it.product(
G.predecessors(node),
G.successors(node)
)
)
G.remove_node(node)
所以G.edges
将返回所需的边( 1->2->3
移动到1->3
和3,4,6,7
成对连接):
OutEdgeView([(1, 3), (3, 6), (3, 7), (4, 6), (4, 7)])
PS我怀疑networkx中是否存在更有效的方法。 在networkx
您应该检查每个节点的前任/后继节点,以便 O 复杂度无论如何都是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.