简体   繁体   中英

fix an ordering of the edges in an undirected networkx graph

In an undirected NetworkX graph edges are represented as Python tuples. their ordering depends on the way you ask for them. Here is a small example what I'm referring to:

import networkx as nx
g = nx.complete_bipartite_graph(2,2)
print(g.edges())
print(g.edges(2))

The output is

[(0, 2), (0, 3), (1, 2), (1, 3)]
[(2, 0), (2, 1)]

Is there a way (not involving manual sorting) to avoid having different representation for an edge?

I'm not sure what you want since in the title you ask for ordered edges but in your example you ask for ordered nodes in the edges. In my examples I show ordering for both. Note that I use list comprehension to create new lists of edges -- the original list of edges ( some_edges ) is unchanged.

First how to sort individual tuples of nodes in a list of edges. That is, edges are in the same order but the nodes in them are sorted.

import networkx as nx
g = nx.Graph()
g.add_edges_from([
    (5, 2),
    (2, 1),
    (3, 2),
    (4, 2)
])
some_edges = g.edges(2)
print("Not sorted:  ", some_edges)

print("SORTED")
# sort nodes in edges
some_edges_1 = [tuple(sorted(edge)) for edge in some_edges]
print("Sorted nodes:", some_edges_1)

And now how to sort edges in a list of edges.

# sort edges in list of edges
some_edges_2 = sorted(some_edges_1)
print("Sorted edges:", some_edges_2)

Output for both blocks of code above:

Not sorted:   [(2, 1), (2, 3), (2, 4), (2, 5)]
SORTED
Sorted nodes: [(1, 2), (2, 3), (2, 4), (2, 5)]
Sorted edges: [(1, 2), (2, 3), (2, 4), (2, 5)]

Here's also an example of reverse sorting where you can actually see the difference between sorting individual edges and sorting a list of edges.

print("Not sorted:  ", some_edges)
print("SORTED REVERSE")
# sort nodes in edges
some_edges_1 = [tuple(sorted(edge, reverse=True)) for edge in some_edges]
print("Sorted nodes:", some_edges_1)
# sort edges in list of edges
some_edges_2 = sorted(some_edges_1, reverse=True)
print("Sorted edges:", some_edges_2)

Output:

Not sorted:   [(2, 1), (2, 3), (2, 4), (2, 5)]
SORTED REVERSE
Sorted nodes: [(2, 1), (3, 2), (4, 2), (5, 2)]
Sorted edges: [(5, 2), (4, 2), (3, 2), (2, 1)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM