"Collapsing" a list into a list of changes

Steven Bethard steven.bethard at gmail.com
Sat Feb 5 18:50:40 EST 2005


Alex Martelli wrote:
> Steven Bethard <steven.bethard at gmail.com> wrote:
> 
> 
>>Here's a solution that works for iterables other than lists:
>>
>>py> def collapse(iterable):
>>...     enumeration = enumerate(iterable)
>>...     _, lastitem = enumeration.next()
>>...     yield lastitem
>>...     for i, item in enumeration:
>>...         if item != lastitem:
>>...             yield item
>>...             lastitem = item
>>...
>>py> lst = [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]
>>py> list(collapse(lst))
>>[0, 1, 2, 3, 2, 4, 5]
>>
>>Again, I'm still not sure I'd call this more elegant...
> 
> 
> Hmmmm, what role does the enumeration play here?

None =) Sorry, it was an accidental carry-over from the list solution 
that looked at lst[i-1].  I thought about correcting it when I realized 
this (after posting), but I was too lazy. ;)

Steve



More information about the Python-list mailing list