I want to group common elements from different sublists and store into a seperate sublist in python.
Example:
myList=[ [1,3] , [2,3] , [1,2] , [6,8] , [5,4] , [5,7] , [8,9] ]
outputList=[ [1,2,3] , [6,8,9] , [4,5,7] ]
as, sublists, [1,3],[2,3] and [1,2] contains common elements so we've made a seperate sublist for [1,2,3]
CodePudding user response:
You can use networkx.
import networkx as nx
# You list
myList =[ [1,3] , [2,3] , [1,2] , [6,8] , [5,4] , [5,7] , [8,9] ]
# Generate new graph
new_graph=nx.Graph()
#add your list as the graph edges
new_graph.add_edges_from(myList)
# Get list of sets of the connected components in the graph
outputList = list(nx.connected_components(new_graph))
print(outputList)
[{1, 2, 3}, {8, 9, 6}, {4, 5, 7}]
CodePudding user response:
i'm not uderstanding on what basis you are wanting the sublists. but here is the code for getting all the unique elements from a list. og_list=[1,3,4,2,1,3,1,3,3,1,2,3,1,3] unique_list=[] for i in og_list: if i not in unique_list: unique_list.append(i) OR you can directly use list comprehension. .i.e.unique_list=[i for i in og_list if i not in unique_list]