Skip to content

Instantly share code, notes, and snippets.

@kipishio
Forked from barrucadu/generator.py
Created May 21, 2018 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kipishio/865684dce264253d0dd19d4348f82752 to your computer and use it in GitHub Desktop.
Save kipishio/865684dce264253d0dd19d4348f82752 to your computer and use it in GitHub Desktop.
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