Networkx:为给定的一组节点创建一个完整的图

ccc*_*ccc 5 graph minimum-spanning-tree networkx python-3.x

我有一个列表作为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)
Run Code Online (Sandbox Code Playgroud)

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

 T_ex= nx.minimum_spanning_tree(G_ex, weight='distance')
 F_ex = list(T_ex.edges())
Run Code Online (Sandbox Code Playgroud)

当我绘制时G_ex,它给了我正确的图形,但是当我打印最小生成树的详细信息时,它显示T_ex.nodes() = [0,1,2,3,56,78,90,112].

有人可以告诉我我正在做的错误吗?

zoh*_*kom 5

不是使用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))
Run Code Online (Sandbox Code Playgroud)

在有向图的情况下,使用:

G_ex.add_edges_from(itertools.permutations(c4_leaves, 2))
Run Code Online (Sandbox Code Playgroud)


SRC*_*SRC 2

这是一个老问题了。然而,我仍然投入了我的两分钱。我面临着同样的问题。我不确定实际问题的阻碍点到底是什么,但我会写下我所做的事情。

因此,我想创建一个包含四个节点(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
Run Code Online (Sandbox Code Playgroud)

这意味着它可以采用迭代器。本着同样的精神,我尝试了以下代码

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: {}})
Run Code Online (Sandbox Code Playgroud)

这样,您就得到了一个由列表构建的完整图表。

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