Home > Software design >  Find elements which appear together in a list of lists
Find elements which appear together in a list of lists

Time:06-21

I have a list of lists in python

results = [[1,2],[2,1],[3,0],[0,3],[3,4],[2,5]]

I want an efficient solution to get the elements which appear together from list of lists.

I want the output to be like:

result = [[1,2,5],[3,0,4]]

The order doesn't matter I am only looking for a solution which is efficient preferably without a ton of loops. Thanks

CodePudding user response:

As you say another approach is OK. I have a solution with networkx as popular with the name networkx.connected_components:

import networkx as nx
results = [[1,2],[2,1],[3,0],[0,3],[3,4],[2,5]]
graph = nx.Graph()
graph.add_edges_from(results)
print([list(c) for c in nx.connected_components(graph)])
# [[1, 2, 5], [0, 3, 4]]
  • Related