This code comes from one of my [gists][1], but could probably be more useful here where it might be easier to find. [1]: https://gist.github.com/JonasAlfredsson/6e30169c5c69813651baf050dbfc7203
1.3 KiB
1.3 KiB
title, tags
| title | tags |
|---|---|
| split_list | list,divmod,intermediate |
Splits a long list into "parts" number of smaller lists, which are as close as possible to each other in length.
- Check if
partsis larger thanlen(lst)in order to not split the list into more parts than there are elements. - The
max(len(lst), 1)check will handle zero length lists, butparts < 1will yield bad results. k = len(lst)//n-> an integer specifying the number of elements in each shorter list (i.e. the quotient).m = len(lst)%n-> iflen(lst)/ndoes not equal a whole number, this equals how many "extra" elements there are (i.e. the remainder).- In order to get
nshort lists, every loop iteration goes toi * kand then take the nextkelements. - If
m > 0, then the early iterations will have one extra element in their list untili > m(no extra elements left). - Return a meta-list containing all these shorter lists.
def split_list(lst: list, parts: int) -> list:
n = min(parts, max(len(lst), 1))
k, m = divmod(len(lst), n)
return [lst[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)]
l = [1, 2, 3, 4, 5, 6]
split_list(l, 2) # [[1, 2, 3], [4, 5, 6]]
split_list(l, 4) # [[1, 2], [3, 4], [5], [6]]
split_list(l, 9) # [[1], [2], [3], [4], [5], [6]]