Networkx:为给定的节点集创建完全图

6

我有一个列表,如下:c4_leaves = [56,78,90,112]。 我想使用c4_leaves中的这些元素作为节点创建完全图。以下是我的尝试:

V_ex = c4_leaves
G_ex = nx.Graph() 
G_ex.add_nodes_from(V_ex)
G_ex = nx.complete_graph(4)

for u,v in G_ex.edges():
    G_ex[u][v]['distance'] = distance(points33, u, v)

然后以上图的最小生成树为:

T_ex = nx.minimum_spanning_tree(G_ex, weight='distance')
F_ex = list(T_ex.edges())

当我绘制G_ex时,它给出了正确的图形,但当我打印最小生成树的详细信息时,它显示T_ex.nodes()=[0,1,2,3,56,78,90,112]。请问有人可以告诉我我的错误在哪里吗?
3个回答

6

不要使用complete_graph函数创建具有其他节点的新完全图,而应按照以下方式创建所需的图:

import itertools
import networkx as nx

c4_leaves = [56,78,90,112]
G_ex = nx.Graph()
G_ex.add_nodes_from(c4_leaves)
G_ex.add_edges_from(itertools.combinations(c4_leaves, 2))

对于有向图,请使用:

G_ex.add_edges_from(itertools.permutations(c4_leaves, 2))

1
这是一个老问题。然而,我仍然想发表一下我的见解。我也遇到了同样的问题。我不确定实际问题的阻碍点是什么,但我会写下我所做的事情。
所以,我想创建一个包含四个节点(56、78、90和112)的完全图。我有一个列表。我查找了complete_graph的定义,以下是我看到的内容。
Signature: nx.complete_graph(n, create_using=None)
Docstring:
Return the complete graph `K_n` with n nodes.

Parameters
----------
n : int or iterable container of nodes
    If n is an integer, nodes are from range(n).
    If n is a container of nodes, those nodes appear in the graph.
create_using : NetworkX graph constructor, optional (default=nx.Graph)
   Graph type to create. If graph instance, then cleared before populated.

Examples
--------
>>> G = nx.complete_graph(9)
>>> len(G)
9
>>> G.size()
36
>>> G = nx.complete_graph(range(11, 14))
>>> list(G.nodes())
[11, 12, 13]
>>> G = nx.complete_graph(4, nx.DiGraph())
>>> G.is_directed()
True

这意味着它可以接受一个迭代器。出于同样的精神,我尝试了以下代码:

In [6]: l = [56,78,90,112]

In [7]: G = nx.complete_graph(l)

In [8]: G.edges(data=True)
Out[8]: EdgeDataView([(56, 78, {}), (56, 90, {}), (56, 112, {}), (78, 90, {}), (78, 112, {}), (90, 112, {})])
    
In [10]: G.nodes(data=True)
Out[10]: NodeDataView({56: {}, 78: {}, 90: {}, 112: {}})

所以,这就是一个由列表构建的完整图。

我希望这回答了这个问题。


0

命令G_ex = nx.complete_graph(4)创建了一个完全图G,其节点为0、1、2和3。然后你可以向G添加更多内容,但它已经有这些节点。


2
谢谢您的回复。但是我该如何删除“0,1,2,3”并添加我想要的内容呢? - ccc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接