Skip to content

Instantly share code, notes, and snippets.

@sweenzor
Created August 28, 2012 05:56
Show Gist options
  • Save sweenzor/3495329 to your computer and use it in GitHub Desktop.
Save sweenzor/3495329 to your computer and use it in GitHub Desktop.
Filter lists in python
#!/usr/bin/env python
from itertools import imap, groupby
from operator import itemgetter
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)))
if __name__ == '__main__':
a = 'AAAABBBCCDAABBB'
print a
print list(_unique_justseen(a)), '\n'
b = [(4,5),(4,4),(5,3),(4,5),(4,5)]
print b
print list(_unique_justseen(b), ), '\n'
grouping = lambda x: x[0]
print b
print list(_unique_justseen(b, key=grouping)), '\n'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment