grouping a flat list of number by range

Gerard Flanagan grflanagan at yahoo.co.uk
Fri Jun 2 01:48:15 EDT 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)
> >
> > i was able to to it without generators/yield but i think it could be
> > better with them, may be do you an idea?
> >
> > best regards,
> >
>
> a list comprehension/itertools version (this won't work with an empty
> list):
>
>     from itertools import groupby
>
>     a = [3, 6, 7, 8, 12, 13, 15]
>
>     result = [[3, 4], [6,9], [12, 14], [15, 16]]
>
>     b = [ list(g)[0] for k,g in groupby(range(a[0],a[-1]+2), lambda x:
> x in a)]
>
>     c = [ b[i:i+2] for i in range(0,len(a),2) ]
>
>     assert c == result
>
>
> Gerard

change len(a) to len(b) in case a has duplicates like
[3,3,3,6,7,8,12,13,15]

Gerard




More information about the Python-list mailing list