Home > OS >  group together consecutive numbers in a list
group together consecutive numbers in a list

Time:12-16

I have an ordered Python list of forms:

[1, 2, 3, 4, 5, 12, 13, 14, 15, 20, 21, 22, 23, 30, 35, 36, 37, 38, 39, 40]

How can I group together consecutive numbers in a list. A group like this:

[[1, 2, 3, 4, 5], [12, 13, 14, 15], [20, 21, 22, 23,], [30], [35, 36, 37, 38, 39, 40]]

I tried using groupby from here but was not able to tailor it to my need. Thanks,

CodePudding user response:

You could use negative indexing:

def group_by_missing(seq):
    if not seq:
        return seq
    grouped = [[seq[0]]]
    for x in seq[1:]:
        if x == grouped[-1][-1]   1:
            grouped[-1].append(x)
        else:
            grouped.append([x])
    return grouped

Example Usage:

>>> lst = [1, 2, 3, 4, 5, 12, 13, 14, 15, 20, 21, 22, 23, 30, 35, 36, 37, 38, 39, 40]
>>> group_by_missing(lst)
[[1, 2, 3, 4, 5], [12, 13, 14, 15], [20, 21, 22, 23], [30], [35, 36, 37, 38, 39, 40]]
  • Related