grouping a flat list of number by range

Paddy paddy3118 at netscape.net
Fri Jun 2 00:36:56 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)
>
> 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,
>
> J.

I did a proceedural version, then re-read your post and did a generator
based version ;-)

=== interv1 ===
>>> inlist = [3, 6, 7, 8, 12, 13, 15]
>>> tmp = []
>>> for i,val in enumerate(inlist):
... 	if i==0:
... 		tmp.append(val)
... 	elif val != valinc:
... 		tmp += [valinc, val]
... 	valinc = val+1
...
>>> tmp.append(valinc)
>>> tmp
[3, 4, 6, 9, 12, 14, 15, 16]
>>> tmp[0::2]
[3, 6, 12, 15]
>>> tmp[1::2]
[4, 9, 14, 16]
>>> zip(tmp[0::2], tmp[1::2])
[(3, 4), (6, 9), (12, 14), (15, 16)]
>>>

=== END interv1 ===

=== interv2 ===
>>> def interv2(inlist):
... 	for i,val in enumerate(inlist):
... 		if i==0:
... 			tmp = val
... 		elif val != valinc:
... 			yield [tmp, valinc]
...                     tmp = val
... 		valinc = val+1
... 	yield [tmp, valinc]
...
>>> list(interv2(inlist))
[[3, 4], [6, 9], [12, 14], [15, 16]]

=== END interv2 ===

- Paddy.




More information about the Python-list mailing list