Dividing a List into Parts of Approximately Equal Length
In Python, the built-in function chunks (provided in the code snippet) can split a list into chunks of a specified size. However, if the list is not divisible by the desired chunk size, it will result in unevenly sized chunks.
To create approximately equal parts, you can use a list generator:
def split(a, n): k, m = divmod(len(a), n) return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))
This function determines the chunk size (k) and the remainder (m) when dividing the list length by the number of parts. It then yields chunks from the list, starting from index i*k and ending at index (i 1)*k. This ensures that the first m chunks include the additional element from the remainder, resulting in approximately equal-sized parts.
Example:
>>> list(split(range(11), 3)) [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10]]
In this example, the list range(11) is split into three parts, resulting in chunks of size 4, 4, and 3.
The above is the detailed content of How to Divide a List into Approximately Equal Parts in Python?. For more information, please follow other related articles on the PHP Chinese website!