关于python:如何将加权的networkx图以所需格式导出到边缘列表?

How to export a weighted networkx graph to edge list in desired format?

我正在尝试获取一个加权的networkx图,并将其转换为edgelist .txt文件,其中每行采用三个以空格分隔的数字形式,表示起始节点,终止节点和相应的权重。

这是我为简单的七节点加权无向图尝试的方法:

1
2
3
4
5
6
 import networkx as nx
 import numpy as np
 A = np.matrix([[0,7,7,0,0],[7,0,6,0,0],[7,6,0,2,1],[0,0,2,0,4],
 [0,0,1,4,0]])
 G = nx.from_numpy_matrix(A)
 nx.write_edgelist(G,"weighted_test_edgelist.txt", delimiter=' ')

已创建文本文件,其外观如下:

1
2
3
4
5
6
7
8
9
10
11
0 1 {'weight': 7}

0 2 {'weight': 7}

1 2 {'weight': 6}

2 3 {'weight': 2}

2 4 {'weight': 1}

3 4 {'weight': 4}

但是,我希望以上内容显示为

1
2
3
4
5
6
7
8
9
10
11
0 1 7

0 2 7

1 2 6

2 3 2

2 4 1

3 4 4

尝试:

1
nx.write_edgelist(G,"weighted_test_edgelist.txt", delimiter=' ', data=['weight'])

输出:

1
2
3
4
5
6
0 1 7
0 2 7
1 2 6
2 3 2
2 4 1
3 4 4

每个文档:

data : bool or list, optional If False write no edge data. If
True write a string representation of the edge data dictionary.. If
a list (or other iterable) is provided, write the keys specified
in the list.