recipes.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import itertools
  2. from .itertoolz import frequencies, pluck, getter
  3. __all__ = ('countby', 'partitionby')
  4. def countby(key, seq):
  5. """ Count elements of a collection by a key function
  6. >>> countby(len, ['cat', 'mouse', 'dog'])
  7. {3: 2, 5: 1}
  8. >>> def iseven(x): return x % 2 == 0
  9. >>> countby(iseven, [1, 2, 3]) # doctest:+SKIP
  10. {True: 1, False: 2}
  11. See Also:
  12. groupby
  13. """
  14. if not callable(key):
  15. key = getter(key)
  16. return frequencies(map(key, seq))
  17. def partitionby(func, seq):
  18. """ Partition a sequence according to a function
  19. Partition `s` into a sequence of lists such that, when traversing
  20. `s`, every time the output of `func` changes a new list is started
  21. and that and subsequent items are collected into that list.
  22. >>> is_space = lambda c: c == " "
  23. >>> list(partitionby(is_space, "I have space"))
  24. [('I',), (' ',), ('h', 'a', 'v', 'e'), (' ',), ('s', 'p', 'a', 'c', 'e')]
  25. >>> is_large = lambda x: x > 10
  26. >>> list(partitionby(is_large, [1, 2, 1, 99, 88, 33, 99, -1, 5]))
  27. [(1, 2, 1), (99, 88, 33, 99), (-1, 5)]
  28. See also:
  29. partition
  30. groupby
  31. itertools.groupby
  32. """
  33. return map(tuple, pluck(1, itertools.groupby(seq, key=func)))