"Collapsing" a list into a list of changes
Steven Bethard
steven.bethard at gmail.com
Fri Feb 4 12:56:03 EST 2005
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?
Well, this does about the same thing, but using enumerate and a list
comprehension:
py> lst = [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]
py> [item for i, item in enumerate(lst) if i == 0 or item != lst[i-1]]
[0, 1, 2, 3, 2, 4, 5]
Similar code that doesn't check 'if i == 0' each time through:
py> itr = enumerate(lst)
py> itr.next()
(0, 0)
py> [lst[0]] + [item for i, item in itr if item != lst[i-1]]
[0, 1, 2, 3, 2, 4, 5]
I don't know if either of these is really more elegant though...
Steve
More information about the Python-list
mailing list