Dividing a List into Nearly Equal Parts
Dividing a list into equal parts is a common task in programming. The built-in chunks() method in Python offers a way to split a list into equally sized chunks, but what if you want to divide the list into roughly equal parts instead?
One approach to achieve this is to 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))
Here's how it works:
Example:
>>> list(split(range(11), 3)) [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10]]
This code splits a list of length 11 into 3 parts, resulting in parts with 4, 4, and 3 elements, respectively.
The above is the detailed content of How to Divide a List into Nearly Equal Parts in Python?. For more information, please follow other related articles on the PHP Chinese website!