我需要使用networkx生成一个全连接的子图,起点是我要连接的节点列表。基本上,我想让我传递给函数的节点列表中的所有节点相互连接。
我想知道是否有任何内置函数可以实现这一点(我还没有找到)?还是我应该考虑一些算法?
非常感谢。
我不知道有没有现成的方法可以做到这一点,但是你可以很容易地模仿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()
有一个用于创建全连接(即完全)图的函数,名为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)
将创建包含所有节点对组合的二元组,这些节点对将作为图中的边。
然而,这种解决方案仅适用于无向图。查看zubinmehta的解决方案以获得更通用的方法。
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.
n>1
替换为len(L)>1
时,这对我起作用了。 - Rasmusnx.complete_graph
和nx.relabel_nodes
来完成。请查看我的回答。 - Joel