如果它们不在预选列表中,如何遍历图中的边

我正在过滤边的子集,以便可以遍历它们。在这种情况下,我排除了“末端边缘”,它们是沿链的最终边缘:


import networkx as nx


graph = nx.Graph()

graph.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 4)])

end_nodes = [n for n in graph.nodes if nx.degree(graph, n) == 1]

end_edges = graph.edges(end_nodes)

print(f"end edges: {end_edges}")

for edge in graph.edges:

    if edge not in end_edges:

        print(f"edge {edge} is not an end edge.")

    else:

        print(f"edge {edge} is an end edge.")

但是,当您运行此代码时,您会得到以下输出:


end edges: [(0, 1), (4, 3)]

edge (0, 1) is an end edge.

edge (1, 2) is an end edge.

edge (2, 3) is an end edge.

edge (3, 4) is an end edge.

Edges (1, 2)and (2, 3)are not in end_edges,但它在检查False条件时返回edge not in end_edges(似乎暗示它实际上被包含,而它似乎不包含)。


发生了什么事,我该如何正确过滤?


Python 版本是 3.7,NetworkX 是 2.4。


动漫人物
浏览 107回答 2
2回答

胡子哥哥

您可以将 end_nodes 转换为一组边并保持边无序。>>> graph = nx.Graph()>>> graph.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 4)])>>> end_nodes = [n for n in graph.nodes if nx.degree(graph, n) == 1]>>> end_edges = set(map(frozenset, graph.edges(end_nodes)))>>> end_edges{frozenset({3, 4}), frozenset({0, 1})}>>> for edge in graph.edges:...     print(edge, frozenset(edge) in end_edges)... (0, 1) True(1, 2) False(2, 3) False(3, 4) True

温温酱

import networkx as nxgraph = nx.Graph()graph.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 4)])end_nodes = [n for n in graph.nodes if nx.degree(graph, n) == 1]end_edges = graph.edges(end_nodes)print(f"end edges: {end_edges}")for edge in graph.edges:    if edge not in list(end_edges):        print(f"edge {edge} is not an end edge.")    else:        print(f"edge {edge} is an end edge.")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python