0
[[[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
iteong
  • 715
  • 3
  • 10
  • 26
  • This looks applicable: [Merging a list of time-range tuples that have overlapping time-ranges](http://stackoverflow.com/q/5679638) – Martijn Pieters Jun 07 '15 at 09:50
  • So how does that function not work? What output did you get? Did you get any errors (give us the full traceback). Help us help you! – Martijn Pieters Jun 07 '15 at 10:04
  • I tried it on merge([[0, 4], [4, 8]]) and got the same. No merging. =( – iteong Jun 07 '15 at 10:06
  • Again, please add that to the question; in comments it is going to get lost. Give us a short section on how you called it, what happened, and what you expected instead. – Martijn Pieters Jun 07 '15 at 10:08
  • "No merging" is not helpful information. To assist you we need to know what the program is supposed to do (which you have described very well indeed) and what it's actually doing (which you've hardly described at all). Please run your program (which as given does nothing but define a function) and include the output in the question. – holdenweb Jun 07 '15 at 14:02

1 Answers1

0

From the link above:

def merge(times):
    saved = list(times[0])
    for st, en in sorted([sorted(t) for t in times]):
        if st <= saved[1]:
            saved[1] = max(saved[1], en)
        else:
            yield list(saved)
            saved[0] = st
            saved[1] = en
    yield list(saved)

>>>mylist = [[[0, 2], [2, 9]], [[3, 7], [7, 9], [9, 12], [15, 17]], [[4, 6]]]
>>>[list(merge(i)) for i in mylist]
[[[0, 9]], [[3, 12], [15, 17]], [[4, 6]]]
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49