pyiter.grouping
1from typing import Callable, DefaultDict, Generic, Iterable, Iterator, List, NamedTuple 2from .transform import Transform, T, K 3from .list_like import ListLike 4 5 6class Grouping(NamedTuple, Generic[K, T]): 7 key: K 8 values: ListLike[T] 9 10 11class GroupingTransform(Transform[T, Grouping[K, T]]): 12 """ 13 A transform that groups elements of an iterable by a key function. 14 """ 15 16 def __init__(self, iter: Iterable[T], key_func: Callable[[T], K]): 17 super().__init__(iter) 18 self.key_func = key_func 19 20 def __do_iter__(self) -> Iterator[Grouping[K, T]]: 21 from collections import defaultdict 22 from .sequence import it 23 24 d: DefaultDict[K, List[T]] = defaultdict(list) 25 for e in self.iter: 26 d[self.key_func(e)].append(e) 27 yield from it(d.items()).map(lambda x: Grouping(x[0], ListLike(x[1])))
class
Grouping(typing.NamedTuple, typing.Generic[~K, ~T]):
Grouping(key, values)
Grouping(key: ~K, values: pyiter.list_like.ListLike[~T])
Create new instance of Grouping(key, values)
Inherited Members
- builtins.tuple
- index
- count
12class GroupingTransform(Transform[T, Grouping[K, T]]): 13 """ 14 A transform that groups elements of an iterable by a key function. 15 """ 16 17 def __init__(self, iter: Iterable[T], key_func: Callable[[T], K]): 18 super().__init__(iter) 19 self.key_func = key_func 20 21 def __do_iter__(self) -> Iterator[Grouping[K, T]]: 22 from collections import defaultdict 23 from .sequence import it 24 25 d: DefaultDict[K, List[T]] = defaultdict(list) 26 for e in self.iter: 27 d[self.key_func(e)].append(e) 28 yield from it(d.items()).map(lambda x: Grouping(x[0], ListLike(x[1])))
A transform that groups elements of an iterable by a key function.