24

我需要从要连接的节点列表开始使用networkx生成一个完全连接的子图。基本上,我希望传递给函数的列表中的所有节点都相互连接。

我想知道是否有任何内置函数可以实现这一点(我还没有找到)?还是我应该考虑一些算法?

非常感谢你。

4

3 回答 3

17

我不知道有什么方法可以做到这一点,但你可以很容易地模仿 networkx 的 complete_graph() 方法并稍微改变它(几乎就像一个内置的):

import networkx
import itertools

def complete_graph_from_list(L, create_using=None):
    G = networkx.empty_graph(len(L),create_using)
    if len(L)>1:
        if G.is_directed():
            edges = itertools.permutations(L,2)
        else:
            edges = itertools.combinations(L,2)
        G.add_edges_from(edges)
    return G

S = complete_graph_from_list(["a", "b", "c", "d"])
print S.edges()
于 2012-05-18T11:09:49.807 回答
12

有一个用于创建完全连接(即完整)图的函数 nameley complete_graph

import networkx as nx
g = nx.complete_graph(10)

它需要一个整数参数(图中的节点数),因此您无法控制节点标签。我还没有找到自动执行此操作的功能,但itertools它很容易:

from itertools import combinations

nodes = ['A', 'B', 'C', 'D', 'E']
edges = combinations(nodes, 2)
g = nx.Graph()
g.add_nodes_from(nodes)
g.add_edges_from(edges)

combinations(nodes, 2)将创建具有所有对组合的 2 元素元组nodes,然后将其用作图中的边。

但是,此解决方案仅对无向图有效。查看zubinmehta 的解决方案以获得更通用的方法。

于 2012-05-18T11:13:37.583 回答
5

您可以使用 networkx 命令直接生成带有整数节点的 clique,然后有一个简单的命令可以使用任何其他可散列名称重新标记节点。

import networkx as nx
L=["hello", "world", "how", "are", "you"]
G=nx.complete_graph(len(L))
nx.relabel_nodes(G,dict(enumerate(L)), copy = False) #if copy = True then it returns a copy.
于 2015-11-26T12:43:37.650 回答