Created
August 28, 2012 05:56
-
-
Save sweenzor/3495329 to your computer and use it in GitHub Desktop.
Filter lists in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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