-
-
Save kipishio/865684dce264253d0dd19d4348f82752 to your computer and use it in GitHub Desktop.
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
def uniques(source, fmap=lambda x: x, restrictOn=lambda x: x): | |
"""Map a function over an iterable, and yield elements which are | |
unique according to the given restriction function. | |
An exception raised in the mapping or restriction function causes | |
that element to be silently skipped. | |
""" | |
seen = set() | |
for thing in source: | |
try: | |
thing = fmap(thing) | |
if restrictOn(thing) in seen: | |
continue | |
seen.add(restrictOn(thing)) | |
yield thing | |
except: | |
continue | |
# example usage: | |
# with open(jsonfile) as f: | |
# data = json.load(f) | |
# for fields in functions.uniques( | |
# data['hits']['hits'], | |
# fmap=lambda hit: hit['_source']['@fields'], | |
# restrictOn=lambda fields: fields['path']): |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment