How to stop Networkx from changing the order of edges when adding them from a list?

前端 未结 2 956
攒了一身酷
攒了一身酷 2021-01-21 08:23

Adding edges from a list to a graph in NetworkX (python) changes the order of the edges, which causes problems for me when drawing the Graph. As example:

import          


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-21 09:18

    The answer to your question is a bit messy because the NetworkX Graph class doesn't retain the order of nodes in an edge. However, this can be circumvented by sorting each edge to guarantee node order. G.edges() can also be sorted by a custom key that retrieves the index that each edge appears in the edge list.

    import networkx as nx
    
    edgelist  = [['C','B'],['A','B'],['A','C']]
    

    First, sort the nodes in each edge and create a dictionary that maps each edge to its index in the edge list:

    edgelist = [sorted(edge) for edge in edgelist]
    mapping = {tuple(edge): index for (edge, index) in zip(edgelist, range(len(edgelist)))}
    

    Then sort the order of the graph's edges according to the index edges in the edge list:

    G = nx.Graph()
    G.add_edges_from(edgelist)
    sorted(G.edges(), key=lambda edge: mapping[tuple(sorted(list(edge)))])
    

提交回复
热议问题