Home > Backend Development > Python Tutorial > How to Divide a List into Approximately Equal Parts in Python?

How to Divide a List into Approximately Equal Parts in Python?

Mary-Kate Olsen
Release: 2024-11-14 15:03:02
Original
923 people have browsed it

How to Divide a List into Approximately Equal Parts in Python?

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))
Copy after login

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]]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template