find non-overlapping blocks in a list
I have a list: x = [[263, 3121], [2201, 4756], [3145, 6423], [4765, 8165], [12480, 18421], [18000, 24191], [26343, 28105], [27341, 28912], [29497, 30282]]
I want a new list that contains the merged overlapping blocks (highlighted above in bold): y = [[263,8165],[12480,24191],[26343,28912],[29497,30282]]
That is, to go through the x-list and merge all overlapping lists to give y. If the first item of the next item of the list in x is smaller than the last item of the previous item in x, then merge the two and save to y, otherwise don't merge just put the new starting value as the next item in y. Continue through x until all overlapping blocks are merged and written into y.
Thank you for your help
You can write down the code just as you described it in the text.
def yield_data(data): start = None end = None for entry in sorted(data): if start is None: start = entry if end is None or entry < end: end = entry else: yield [start, end] start, end = entry yield [start, end] def main(): x = [[263, 3121], [2201, 4756], [3145, 6423], [4765, 8165], [12480, 18421], [18000, 24191], [26343, 28105], [27341, 28912], [29497, 30282]] for group in yield_data(x): print(group) if __name__ == '__main__': main()
The compares to None are used to initialize the data in the first loop.