0

What I'm trying to do is take a list and filter it based on comparisons of adjacent list members. Namely, something like this

filter(lambda x,y: x != y, someList)

to get rid of duplicate elements right next to each other. I can easily implement this other ways, but started out trying to do it with a list reduction/filter and am stubborn enough to want to keep trying until I figure it out. I am still not that experienced in python, but I feel like there is something like this that I am missing.

Thanks!

1
  • What other ways have you considered? It'd help if you post those (and is someList actually a list or sequence or some arbitrary iterable) etc... (desired input and output samples would also be good) Commented Feb 22, 2013 at 5:15

2 Answers 2

4
def unique_justseen(iterable, key=None):
    "List unique elements, preserving order. Remember only the element just seen."
    # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
    # unique_justseen('ABBCcAD', str.lower) --> A B C A D
    return imap(next, imap(itemgetter(1), groupby(iterable, key)))

Source: Python Documentation, 9.7.2. Recipes.

There's a wealth of great stuff in itertools for efficient looping.

Sign up to request clarification or add additional context in comments.

Comments

3

For consecutive elements (duplicate elements) then:

>>> from itertools import groupby
>>> items = 'aaaabbdeeeeefg'
>>> ''.join(k for k, g in groupby(items))
'abdefg'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.