Search code examples
pythonnodesnetworkxgraph-theoryedges

How to get the corresponding edges from a list of nodes


I have a list of nodes in a form similar to this: Nodelist=[[1,2,3],[4,7,6],[7,2,9]] Such that there is an edge that connects them, for example 1 is connected to 2 and 2 to 3. These are not the complete set of nodes in my graph.

What I want to do is return a list of edges if there is a connection between the two nodes in Nodelist. i.e. output=[(1,2),(2,3),(3,1),...]

What I know already, every node in a sublist of Nodelist is connected, i.e there is an edge between (1,2),(2,3),(3,1).

I hope what i'm asking makes sense, any help would be appreciated. Please let me know if I need to clarify on anything.


Solution

  • Try this:

    from itertools import combinations
    
    [list(combinations(x, 2)) for x in node_list] 
    

    combinations gives all combinations of a list of the given size. So combinations([1,2,3], 2) would give you [(1,2), (2,3), (3,1)] Just do that for each of the node_lists.