Is there something existing in python that can convert an increasing list of integers into a range list
E.g. given the set {0, 1, 2, 3, 4, 7, 8, 9, 11} I want to get
This is an improvement over the very elegant answer. This one covers non-unique and non-sorted input and is python3 compatible too:
import itertools
def to_ranges(iterable):
iterable = sorted(set(iterable))
for key, group in itertools.groupby(enumerate(iterable),
lambda t: t[1] - t[0]):
group = list(group)
yield group[0][1], group[-1][1]
Example:
>>> x
[44, 45, 2, 56, 23, 11, 3, 4, 7, 9, 1, 2, 2, 11, 12, 13, 45]
>>> print( list(to_ranges(x)))
[(1, 4), (7, 7), (9, 9), (11, 13), (23, 23), (44, 45), (56, 56)]