"Collapsing" a list into a list of changes

Jack Diederich jack at performancedrivers.com
Fri Feb 4 13:02:36 EST 2005


On Fri, Feb 04, 2005 at 12:43:37PM -0500, Alan McIntyre wrote:
> Hi all,
> 
> I have a list of items that has contiguous repetitions of values, but 
> the number and location of the repetitions is not important, so I just 
> need to strip them out.  For example, if my original list is 
> [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5], I want to end up with [0,1,2,3,2,4,5].
> 
> Here is the way I'm doing this now:
> 
> def straightforward_collapse(myList):
>     collapsed = [myList[0]]
>     for n in myList[1:]:
>         if n != collapsed[-1]:
>             collapsed.append(n)
> 
>     return collapsed
> 
> Is there an elegant way to do this, or should I just stick with the code 
> above?
> 
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