Starting from your initial list of lists:
>>> g = [[0, 7],
[1, 2, 10, 19],
[3, 4, 5, 6, 15, 21, 24, 27],
[0, 7, 8, 9, 12, 17],
[1, 10, 11, 20],
[8, 12, 13, 18],
[14, 25],
[3, 15, 16, 22],
[9, 13, 17, 18]]
As you work through, I think what you want is to combine all matching sublists in the rest of the list into the current sublist, then remove them from the original list:
>>> for start_index, start in enumerate(g):
while True:
for end_index, end in enumerate(g[start_index+1:],
start_index+1):
if any(x == y for x in start for y in end):
g[start_index].extend(end)
del g[end_index]
break
else:
break
>>> g
[[0, 7, 0, 7, 8, 9, 12, 17, 8, 12, 13, 18, 9, 13, 17, 18],
[1, 2, 10, 19, 1, 10, 11, 20],
[3, 4, 5, 6, 15, 21, 24, 27, 3, 15, 16, 22],
[14, 25]]
Then all you have to do is get rid of duplicates:
>>> [sorted(set(l)) for l in g]
[[0, 7, 8, 9, 12, 13, 17, 18],
[1, 2, 10, 11, 19, 20],
[3, 4, 5, 6, 15, 16, 21, 22, 24, 27],
[14, 25]]
This is relatively inefficient, but provides you a starting point for enhancement (for example, if start
and end
were already sets, start & end
could replace the any
).