Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/toolz/recipes.py: 56%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import itertools
2from .itertoolz import frequencies, pluck, getter
5__all__ = ('countby', 'partitionby')
8def countby(key, seq):
9 """ Count elements of a collection by a key function
11 >>> countby(len, ['cat', 'mouse', 'dog'])
12 {3: 2, 5: 1}
14 >>> def iseven(x): return x % 2 == 0
15 >>> countby(iseven, [1, 2, 3]) # doctest:+SKIP
16 {True: 1, False: 2}
18 See Also:
19 groupby
20 """
21 if not callable(key):
22 key = getter(key)
23 return frequencies(map(key, seq))
26def partitionby(func, seq):
27 """ Partition a sequence according to a function
29 Partition `s` into a sequence of lists such that, when traversing
30 `s`, every time the output of `func` changes a new list is started
31 and that and subsequent items are collected into that list.
33 >>> is_space = lambda c: c == " "
34 >>> list(partitionby(is_space, "I have space"))
35 [('I',), (' ',), ('h', 'a', 'v', 'e'), (' ',), ('s', 'p', 'a', 'c', 'e')]
37 >>> is_large = lambda x: x > 10
38 >>> list(partitionby(is_large, [1, 2, 1, 99, 88, 33, 99, -1, 5]))
39 [(1, 2, 1), (99, 88, 33, 99), (-1, 5)]
41 See also:
42 partition
43 groupby
44 itertools.groupby
45 """
46 return map(tuple, pluck(1, itertools.groupby(seq, key=func)))