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

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

我正在尝试采用加权 networkx 图并将其转换为边缘列表 .txt 文件,其中每一行采用三个 space 分隔的数字的形式,表示起始节点、结束节点、以及相应的权重。

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

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

文本文件已创建,如下所示:

0 1 {'weight': 7}

0 2 {'weight': 7}

1 2 {'weight': 6}

2 3 {'weight': 2}

2 4 {'weight': 1}

3 4 {'weight': 4}

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

0 1 7

0 2 7

1 2 6

2 3 2

2 4 1

3 4 4

尝试:

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

输出:

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.