Guest User

Untitled

a guest
Jan 18th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.50 KB | None | 0 0
  1. from typing import TypeVar, Hashable, Callable, Set, Iterable, Iterator
  2.  
  3. T = TypeVar("T")
  4. K = TypeVar("K", bound=Hashable)
  5.  
  6.  
  7. def keyed_filter(iterable: Iterable[T], key: Callable[[T], K]) -> Iterator[T]:
  8. """Yields the iterable without key duplicates.
  9.  
  10. >>> list(keyed_filter(["Alice","Adam","Bob","Ben"],key=lambda x:x[0]) )
  11. ['Alice', 'Bob']
  12. """
  13. seen_values: Set[K] = set()
  14. for val in (val for val in iterable if key(val) not in seen_values):
  15. seen_values.add(key(val))
  16. yield val
Add Comment
Please, Sign In to add comment