代码之家  ›  专栏  ›  技术社区  ›  Simon C.

以邻接列表的形式将Graph写入文件[在每行中提及每个节点的所有邻居]

  •  1
  • Simon C.  · 技术社区  · 10 年前

    我需要在一个文本文件中编写一个图表,其中文件的每一行由一个节点组成,然后是所有相邻节点。基本上是 Adjacency List 是,函数是什么 write_adjlist 应该做的。不幸的是,事实并非如此,因为边缘没有被复制。在维基百科的例子中,邻接列表是:

    a与b相邻,c

    b与a、c相邻

    c与a、b相邻

    我们可以看到所有边都出现了两次(边 (a,b) 在第1行和第2行,边缘 (b,c) 第2行和第3行…)。

    但现在,如果我使用以下代码生成一个小世界网络:

    import networkx as nx
    
    N=5  #Number of nodes
    v=2  #Number of neighbours
    p=.1 #rewiring proba
    
    G = nx.connected_watts_strogatz_graph(N,v,p)
    nx.write_adjlist(G.to_undirected(),"test.txt")
    

    它给了我:

    #adj.py
    # GMT Thu Jan 21 06:57:29 2016
    # watts_strogatz_graph(5,2,0.1)
    0 1 4
    1 2
    2 3
    3 4
    4
    

    我想去哪

    0 1 4
    1 2 0
    2 3 1
    3 2 4 
    4 0 3
    

    你知道我该怎么做才能得到我想要的输出吗?

    1 回复  |  直到 10 年前
        1
  •  1
  •   Abdallah Sobehy    10 年前

    实际上,这就是 write_adjlist 定义为,以便按照您的需要编写文件。可以使用以下函数进行简单的解决:

    def adj_list_to_file(G,file_name):
        f = open('tst.txt', "w")
        for n in G.nodes():
            f.write(str(n) + ' ')
            for neighbor in G.neighbors(n):
                f.write(str(neighbor) + ' ')
            f.write('\n')
    
    N=5  #Number of nodes
    v=2  #Number of neighbours
    p=.1 #rewiring proba
    G = nx.connected_watts_strogatz_graph(N,v,p)
    nx.draw(G, with_labels= True)
    plt.show()
    adj_list_to_file(G.to_undirected(),"tst.txt")
    

    文件输出为:

    0 1 4 
    1 0 2 
    2 1 3 
    3 2 4 
    4 0 3