Keep in a Graph only those edges in a list

Question:

I have this list of edges (tuples) called edgesKeep that I want to KEEP in the graph, and remove all other edges. In my case (because of how edgesKeep is built), there is no guarantee that the node names in edges of edgesKeep follow the same order of node names in G.edges (an edge can be ('u','v') in one and appear as ('v','u') in the other one). So I have to do this:

G.remove_edges_from(e for e in G.edges if e not in edgesKeep and tuple(reversed(e)) not in edgesKeep)

Is there a way to make it simpler? I mean, somehow getting rid of tuple(reversed(e)) not in edgesKeep ?

Asked By: Diego Rubert

||

Answers:

You could sort the tuples in edgesKeep and do

G.remove_edges_from(e for e in G.edges if sorted(e) not in edgesKeep)
Answered By: Tom McLean
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.