giving the paired nodes and a list of random nodes, find and group the nodes that are connected in python

Question:

saying I have a list of pairs like
pairs = [[0,10],[0,1],[0,2],[1,7],[2,3],[2,4],[3,8],[4,5],[5,6],[8,9]]
and a list
a = [3,4,5,6,8,9].
Based on given pairs, how to group list, a, into [[3,8,9],[4,5,6]]? Any idea? Thanks in advance.

Asked By: ying zhang

||

Answers:

You can use for this, with the subgraph and connected_components methods:

import networkx as nx

pairs = [[0,10],[0,1],[0,2],[1,7],[2,3],[2,4],[3,8],[4,5],[5,6],[8,9]]
a = [3,4,5,6,8,9]

G = nx.from_edgelist(pairs)

out = list(nx.connected_components(G.subgraph(a)))

Output: [{3, 8, 9}, {4, 5, 6}]

Answered By: mozway
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.