Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - find incremental numbered sequences with a list comprehension [duplicate]

I have a sequence of numbers in a list and I'm looking for an elegant solution, preferably list comprehension, to get the individual sequences (including single values). I have solved this small problem but it is not very pythonic.

The following list defines an input sequence:

input = [1, 2, 3, 4, 8, 10, 11, 12, 17]

The desired output should be:

output = [
  [1, 2, 3, 4],
  [8],
  [10, 11, 12],
  [17],
]
like image 330
skovsgaard Avatar asked May 01 '13 08:05

skovsgaard


2 Answers

>>> from itertools import groupby, count
>>> nums = [1, 2, 3, 4, 8, 10, 11, 12, 17]
>>> [list(g) for k, g in groupby(nums, key=lambda n, c=count(): n - next(c))]
[[1, 2, 3, 4], [8], [10, 11, 12], [17]]
like image 116
jamylak Avatar answered Nov 16 '22 04:11

jamylak


Pythonic means simple, straightforward code, and not one-liners.

def runs(seq):
    result = []
    for s in seq:
        if not result or s != result[-1][-1] + 1:
            # Start a new run if we can't continue the previous one.
            result.append([])
        result[-1].append(s)
    return result

print runs([1, 2, 3, 4, 8, 10, 11, 12, 17])
like image 23
Paul Hankin Avatar answered Nov 16 '22 03:11

Paul Hankin