"Collapsing" a list into a list of changes
Mike C. Fletcher
mcfletch at rogers.com
Fri Feb 4 13:59:12 EST 2005
Alan McIntyre wrote:
...
> 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].
...
> Is there an elegant way to do this, or should I just stick with the
> code above?
>>> def changes( dataset ):
... last = None
... for value in dataset:
... if value != last:
... yield value
... last = value
...
>>> print list(changes(data ))
which is quite readable/elegant IMO.
Have fun,
Mike
________________________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://www.vrplumber.com
http://blog.vrplumber.com
PyCon is coming...
More information about the Python-list
mailing list