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

Write a Graph into a file in an adjacency list form [mentioning all neighbors of each node in each line]

我需要在文本文件中写一个图,其中文件的每一行都由一个节点和其所有邻居组成。它基本上就是 Adjacency List 是什么,以及函数 write_adjlist 应该做什么。不幸的是,情况并非如此,因为边缘没有被复制。在维基百科的例子中,邻接表是:

a adjacent to b, c

b adjacent to a, c

c adjacent to a, b

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

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

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

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

实际上这就是 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