grouping a flat list of number by range

Gerard Flanagan grflanagan at yahoo.co.uk
Sat Jun 3 21:27:41 CEST 2006


joh12005 at yahoo.fr wrote:
> hello,
>
> i'm looking for a way to have a list of number grouped by consecutive
> interval, after a search, for example :
>
> [3, 6, 7, 8, 12, 13, 15]
>
> =>
>
> [[3, 4], [6,9], [12, 14], [15, 16]]
>
> (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 =>
> [6:9], and so on)


Just another 'itertools.groupby' variation.  It considers the whole
range of numbers spanned by the dataset - eg. in your example,
range(3,17) - so possibly not very efficient if the range is large and
the data sparse within the range.

def get_intervals(data):
  intervals = [ [], [] ]
  for k,g in groupby(range(data[0],data[-1]+2), lambda x:x in data):
    intervals[k].append( list(g)[0] )  #k is 0 or 1
  return zip(intervals[1],intervals[0])

a = [3, 6, 7, 8, 12, 13, 15]

assert get_intervals(a) == [(3,4),(6, 9),(12,14),(15,16)]   


Gerard




More information about the Python-list mailing list