我有一个使用NetworkX构建的图,并且需要打印 Node-Node-EdgeWeight 详细信息,因为我对每个节点作为源进行图的 DFS 遍历。 / p>
我在遍历 node-node 详细信息时很成功,但是在遍历时也需要边缘属性。
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_edge("A", "B", weight=1)
G.add_edge("B", "C", weight=2)
G.add_edge("B", "D", weight=3)
G.add_edge("D", "E", weight=4)
G.add_edge("B", "E", weight=5)
G.add_edge("A", "E", weight=6)
for node in G.nodes:
print(list(nx.dfs_tree(G, source=node)))
for node in G.nodes:
print(list(nx.dfs_edges(G, source=node)))
预期输出:
[('A','B', 1 ),('B','C', 2 ),('B','D', 3 ),('D','E', 4 )]
[('B','C', 2 ),('B','D', 3 ),(“ D”,“ E”, 4 )]
....
实际输出:
[('A','B'),('B','C'),('B','D'),('D','E')]
[('B','C'),('B','D'),('D','E')]
...
答案 0 :(得分:1)
使用G上的get_edge_data访问重量。例如,
import networkx as nx
G = nx.DiGraph()
G.add_edge("A", "B", weight=1)
G.add_edge("B", "C", weight=2)
G.add_edge("B", "D", weight=3)
G.add_edge("D", "E", weight=4)
G.add_edge("B", "E", weight=5)
G.add_edge("A", "E", weight=6)
for node in G.nodes:
for edge in list(nx.dfs_edges(G, source=node)):
print edge[0], edge[1], G.get_edge_data(edge[0],edge[1])['weight']
输出为:
A B 1
B C 2
B E 5
B D 3
B C 2
B E 5
B D 3
D E 4