grouping a flat list of number by range

Peter Otten __peter__ at web.de
Thu Jun 1 17:53:41 EDT 2006


joh12005 at yahoo.fr wrote:

> 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?

Don't hold back your code. Would it work to replace each occurrence of

result_list.append([start, stop]) 

with 

yield [start, stop]

?

Peter



More information about the Python-list mailing list