utils.py 620 B

1234567891011121314151617181920212223242526272829
  1. """
  2. Utility functions
  3. """
  4. def chunks(it, n):
  5. """Split an iterator into chunks with ``n`` elements each.
  6. Examples
  7. # n == 2
  8. >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 2)
  9. >>> list(x)
  10. [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10]]
  11. # n == 3
  12. >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 3)
  13. >>> list(x)
  14. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]
  15. """
  16. acc = []
  17. for i, item in enumerate(it):
  18. if i and not i % n:
  19. yield acc
  20. acc = []
  21. acc.append(item)
  22. yield acc