I need to group sublists with the same elements together
For example:
list1 =[[1, 0], [2, 1], [30, 32]]
would link [1, 0]
and [2, 1]
together since they both contain 1
and those two would combine into [0, 1, 2]
So after linking, the new list should be like:
new_list1 = [[1, 0, 2], [30, 32]]
IE: there shouldn't be same number inside a sub-list and order is not important.
A longer example:
list2 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [13, 14], [30, 32]]
after linking, it would be
new_list2 = [[2, 3, 4], [6, 5, 7, 8], [13, 14], [30, 32]]
So how can this be done in a general way?
To group the sublists in a general way you can:
Code:
def linking_sublists(lists):index = {}sets = []for l in lists:found = Nonefor i in l:if i in index:# this list has an element we have already seenif found:# combine two setsto_remove = index[i]if found != to_remove:for j in index[i]:found.add(j)index[j] = foundto_remove.clear()else:found = index[i]if found is not None:s = foundfor i in l:s.add(i)else:s = set(l)sets.append(s)for i in l:index[i] = sreturn [list(sorted(s)) for s in sets if s]
How:
This function uses sets and an index dict
to group any list with matching elements into sets and track which elements are already in a set
.
Test Code:
list_2 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [13, 14], [30, 32]]
print(linking_sublists(list_2))list_3 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [30, 32], [4, 5], [3, 4]]
print(linking_sublists(list_3))
Results:
[[2, 3, 4], [5, 6, 7, 8], [13, 14], [30, 32]]
[[2, 3, 4, 5, 6, 7, 8], [30, 32]]