3

我正在嘗試實現tarjan的算法。 我決定生成一個隨機圖作爲算法的輸入,一次添加一條邊。網絡x中邊緣列表的自定義輸出

我生成的隨機圖形,並在文件中保存它,如下圖所示

from networkx import * 
import sys 
import matplotlib.pyplot as plt 

n = 10 # 10 nodes 
m = 20 # 20 edges 

G = gnm_random_graph(n, m) 

# print the adjacency list to a file 
try: 
    nx.write_edgelist(G, "test.edgelist", delimiter=',') 
except TypeError: 
    print "Error in writing output to random_graph.txt" 

fh = open("test.edgelist", 'rb') 
G = nx.read_adjlist(fh) 
fh.close() 

,我在test.edgelist文件得到的是這樣的輸出。

0,4,{} 
0,5,{} 
0,6,{} 
1,8,{} 
1,3,{} 
1,4,{} 
1,7,{} 
2,8,{} 
2,3,{} 
2,5,{} 
3,8,{} 
3,7,{} 
4,8,{} 
4,9,{} 
5,8,{} 
5,9,{} 
5,7,{} 
6,8,{} 
6,7,{} 
7,9,{} 

如何過,在我已經實現了的Tarjan的算法,輸入格式爲

add_edge(1,2) 
add_edge(2,3) 
.... 

我希望用在一個循環中隨機生成的圖形,得到輸入。

如何獲取{}? 此外,如果有一些更好的方法來實現這一點,請幫助,因爲對於海量數據集,難以將其保存爲單個列表(add_edge()將邊緣添加到列表中)

回答

3

你必須用一套data參數所有邊緣數據下降到False

nx.write_edgelist(G, "test.edgelist", delimiter=',', data = False) 

輸出:

0,3 
0,4 
0,1 
0,8 
0,6 
0,7 

但是,如果你想保存邊緣自己的格式使用週期喜歡這裏:

from networkx import gnm_random_graph 

n = 10 # 10 nodes 
m = 20 # 20 edges 

G = gnm_random_graph(n, m) 

# iterate over all edges 
with open('./test.edgelist', 'w') as f: 
    for edge in G.edges(): 
     f.write("add_edge{0}\n".format(edge)) 

輸出:

add_edge(0, 7) 
add_edge(0, 4) 
add_edge(0, 8) 
add_edge(0, 3) 
add_edge(0, 2) 
add_edge(1, 5) 
add_edge(1, 6) 
add_edge(1, 7) 
add_edge(2, 5) 
add_edge(2, 4) 
add_edge(2, 9) 
add_edge(2, 8) 
add_edge(2, 3) 
add_edge(3, 9) 
add_edge(3, 5) 
add_edge(4, 9) 
add_edge(4, 7) 
add_edge(5, 9) 
add_edge(6, 9) 
add_edge(7, 9)