简体   繁体   English

networkx中边缘列表的自定义输出

[英]Custom output of edgelist in networkx

I am trying to implement tarjan's algorithm for practice. 我正在尝试实现tarjan的算法。 I decided to generate a random graph to give as input to the algorithm, adding one edge at a time. 我决定生成一个随机图,作为算法的输入,一次添加一个边。

I generated the random graph and saved it in a file, as shown below 我生成了随机图并将其保存在文件中,如下所示

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()

The output that I got in the test.edgelist file is something like this. 我在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,{}

How ever, in the tarjan's algorithm that I've implemented, the input is in the format 但是,在我实现的tarjan算法中,输入采用的是格式

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

I wish to use the randomly generated graph in a loop to give as input. 我希望在循环中使用随机生成的图形作为输入。

How do i not get the {}? 我怎么没有得到{}? Also, if there is some better way to implement this, please help, since, for a massive dataset, it'll be difficult to save it an a single list(add_edge() adds the edge to a list) 此外,如果有更好的方法来实现这一点,请帮助,因为,对于一个大型数据集,将它保存为单个列表将很困难(add_edge()将边添加到列表中)

You have to drop all edges data with set data parameter to False : 您必须使用set data参数将所有边数据删除为False

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

Output: 输出:

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

However if you want to save edges in your own format use a cycle like here: 但是,如果您想以自己的格式保存边缘,请使用以下循环:

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))

Output: 输出:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM