Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from typing import TypeVar, Hashable, Callable, Set, Iterable, Iterator
- T = TypeVar("T")
- K = TypeVar("K", bound=Hashable)
- def keyed_filter(iterable: Iterable[T], key: Callable[[T], K]) -> Iterator[T]:
- """Yields the iterable without key duplicates.
- >>> list(keyed_filter(["Alice","Adam","Bob","Ben"],key=lambda x:x[0]) )
- ['Alice', 'Bob']
- """
- seen_values: Set[K] = set()
- for val in (val for val in iterable if key(val) not in seen_values):
- seen_values.add(key(val))
- yield val
Add Comment
Please, Sign In to add comment