grouping a flat list of number by range

Ben Cartwright bencvt at gmail.com
Fri Jun 2 00:16:33 CEST 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?

Sure:

    def group_intervals(it):
        it = iter(it)
        val = it.next()
        run = [val, val+1]
        for val in it:
            if val == run[1]:
                run[1] += 1
            else:
                yield run
                run = [val, val+1]
        yield run

--Ben




More information about the Python-list mailing list