Created
October 31, 2020 15:58
-
-
Save hughdbrown/6e6439175dd640aac67b4481730b34e5 to your computer and use it in GitHub Desktop.
Chunk items into groups of size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> def chunk(items, size): | |
... i, count = 0, len(items) | |
... for j in reversed(range(1, size + 1)): | |
... m, n = divmod(count, j) | |
... k = m + int(bool(n)) | |
... yield items[i:i + k] | |
... i += k | |
... count -= k | |
... | |
>>> list(chunk(range(5), 5)) | |
[[0], [1], [2], [3], [4]] | |
>>> list(chunk(range(6), 5)) | |
[[0, 1], [2], [3], [4], [5]] | |
>>> list(chunk(range(7), 5)) | |
[[0, 1], [2, 3], [4], [5], [6]] | |
>>> list(chunk(range(14), 5)) | |
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13]] | |
>>> list(chunk(range(15), 5)) | |
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]] |
Pro: Simplest code
Con: The stride groups items in an unexpected way
>>> def chunk(items, size):
... for j in range(size):
... yield items[j::size]
...
>>> list(chunk(range(14), 5))
[[0, 5, 10], [1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9]]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pro: Fewer variables
Con: groups of items are in reverse order