"Collapsing" a list into a list of changes

Alan McIntyre alan.mcintyre at esrgtech.com
Fri Feb 4 13:15:12 EST 2005


Jack,

I'm not using 2.4 yet; still back in 2.3x. :)  Thanks for the examples, 
though - they are clear enough that I will probably use them when I upgrade.

Thanks,
Alan

Jack Diederich wrote:
> If you are using python2.4,
> 
> 
>>>>import itertools as it
>>>>[x[0] for (x) in it.groupby([0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5])]
> 
> [0, 1, 2, 3, 2, 4, 5]
> 
> 
> Since this is 2.4 you could also return a generator expression.
> 
> 
>>>>def iter_collapse(myList):
> 
> ...   return (x[0] for (x) in it.groupby([0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]))
> ... 
> 
>>>>i = iter_collapse([0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5])
>>>>i
> 
> <generator object at 0xb7df6b2c>
> 
>>>>list(i)
> 
> [0, 1, 2, 3, 2, 4, 5]
> 
> 
> 
> -Jack
> 



More information about the Python-list mailing list