"Collapsing" a list into a list of changes

Francis Girard francis.girard at free.fr
Sun Feb 6 16:30:25 EST 2005


This is a prefect use case for the good old "reduce" function:

--BEGIN SNAP

a_lst = [None,0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]

def straightforward_collapse(lst):
  return reduce(lambda v,e: v[-1]!=e and v+[e] or v, lst[1:], [lst[0]])

def straightforward_collapse_secu(lst):
  return lst and reduce(lambda v,e: v[-1]!=e and v+[e] or v, lst[1:], 
[lst[0]]) or []
  
print straightforward_collapse(a_lst)
print straightforward_collapse_secu([])

--END SNAP

Regards

Francis Girard

Le vendredi 4 Février 2005 20:08, Steven Bethard a écrit :
> Mike C. Fletcher wrote:
> > 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.
>
> But fails if the list starts with None:
>
> py> lst = [None,0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]
> py> def changes(dataset):
> ...     last = None
> ...     for value in dataset:
> ...         if value != last:
> ...             yield value
> ...         last = value
> ...
> py> list(changes(lst))
> [0, 1, 2, 3, 2, 4, 5]
>
> A minor modification that does appear to work:
>
> py> def changes(dataset):
> ...     last = object()
> ...     for value in dataset:
> ...         if value != last:
> ...             yield value
> ...         last = value
> ...
> py> list(changes(lst))
> [None, 0, 1, 2, 3, 2, 4, 5]
>
> STeVe




More information about the Python-list mailing list