[[[0, 2], [2, 9]], [[3, 7], [7, 9], [9, 12], [15, 17]], [[4, 6]]]
I need to iterate through this list of sublists of list pairs and check whether the next pair in the sublist has its first number same as the second number of the previous pair. If it is the same, merge.
So what it needs to do is merge [0, 2]
and [2, 9]
to get [0, 9]
and merge ONLY [3, 7],[7, 9],[9, 12]
to get [3, 12]
but don't touch [15, 17]
, so the second sublist sublist will end up becoming [[3, 12], [15, 17]]
and finally the main list becomes:
[[[0, 9]], [[3, 12], [15, 17]], [[4, 6]]]
How do I do that? I tried the following but it doesn't work:
def merge(lst_of_lsts):
res = []
for sublist in lst_of_lsts:
for i, ressublists in enumerate(res):
if sublist[1]==ressublists[0]:
res[i] += ([sublist[0],ressublists[-1]])
break
else:
res.append(sublist)
return res