【问题标题】:Networkx: Creating a complete graph for a given set of nodesNetworkx:为给定的一组节点创建一个完整的图
【发布时间】:2018-09-21 16:22:05
【问题描述】:

我有一个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]

谁能告诉我我正在做的错误?

【问题讨论】:

    标签: python-3.x graph networkx minimum-spanning-tree


    【解决方案1】:

    不要使用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))
    

    【讨论】:

      【解决方案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
      

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

      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: {}})
      

      所以,你有了它,一个由列表构建的完整图表。

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

      【讨论】:

        【解决方案3】:

        命令G_ex = nx.complete_graph(4) 创建一个完整的图G,其节点为0、1、2 和3。然后您向G 添加更多,但它具有这些节点。

        【讨论】:

        • 谢谢。但是如何删除“0,1,2,3”并添加我想要的内容?
        猜你喜欢
        • 1970-01-01
        • 2015-02-05
        • 1970-01-01
        • 2014-01-17
        • 1970-01-01
        • 2016-01-01
        • 1970-01-01
        • 2021-08-13
        • 1970-01-01
        相关资源
        最近更新 更多