grouping a flat list of number by range

Steven Bethard steven.bethard at gmail.com
Sun Jun 4 00:21:07 CEST 2006


Gerard Flanagan wrote:
> 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])

If you're gonna go this route, you should definitely use a set to check 
containment; ``x in data`` is going to be costly for long lists. 
Defining your key something like the following would be better::

     data_set = set(data)
     def key(x):
         return x in data_set

STeVe




More information about the Python-list mailing list