[Tutor] how to remove the coming duplication
Peter Otten
__peter__ at web.de
Thu Nov 10 10:45:59 CET 2011
Asokan Pichai wrote:
> On Thu, Nov 10, 2011 at 2:07 PM, Peter Otten <__peter__ at web.de> wrote:
>
>> Christian Witts wrote:
>>
>> > def remove_coming_duplication(a_list):
>> > return [element for idx, element in enumerate(a_list) if element
>> > !=
>> > a_list[idx-1]]
>>
>> Beware of negative indices:
>>
>> >>> remove_coming_duplication([1, 2, 1])
>> [2, 1] # should be [1, 2, 1]
>>
>>
> I ran into that and hence I chose to zip, compare and add the last element
I have one for you, too ;)
>>> def no_adjacent_dup(lst):
... return [ x for x, y in zip(lst, lst[1:]) if x != y] + [lst[-1]]
...
>>> no_adjacent_dup([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in no_adjacent_dup
IndexError: list index out of range
And a subtle one as a bonus:
>>> no_adjacent_dup([1, 1.0])
[1.0] # should be 1
Here's a highlevel approach, probably not very efficient:
>>> from itertools import groupby
>>> [k for k, g in groupby([1, 1.0, 2, 1, 3, 3, 3])]
[1, 2, 1, 3]
More information about the Tutor
mailing list