Skip to main content
 首页 » 编程设计

python之使用 networkx 将图形转换为完整图形的最快方法

2025年04月02日8arxive

我想比较两个图的性能,第二个是 K n 完整图。我们将 G 称为第一个图(非完整图),将 H 称为第二个图(K n 图)。我希望 H 中的节点具有与 G 中的节点完全相同的属性(和相对值),因此(显然)我不能只运行 networkx.complete_graph(n)。我的第一个想法是使用这段代码:

H = G.copy() 
nh = H.nodes() 
eh = H.edges() # I create those variables in hope to save some speed 
for u in nh: 
    for v in filter(lambda x: x > u, nh): # it's an undirected graph, saves some speed 
        if (u,v) not in eh: 
            H.add_edge(u,v) 

但是,由于我的图表有 10,000 多个节点,因此这个过程变得相当缓慢。有什么办法可以加快速度吗?

请您参考如下方法:

好的,我可能已经找到答案了:

H = networkx.complete_graph(n) 
labels = nx.get_node_attributes(G,attribute) 
nx.set_node_attributes(H,attribute,labels) 

有没有人有更快的选择?