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

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

Barbara Streisand
Release: 2024-11-16 10:23:02
Original
1018 people have browsed it

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

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

Here's how it works:

  • k is the number of items in each part, and m is the remainder from dividing the list length by n.
  • The for loop iterates over the desired number of parts n.
  • For each part, it calculates the starting and ending indices based on k, m, and the current iteration i.
  • The slice a[start:end] extracts the elements for the current part.

Example:

>>> list(split(range(11), 3))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10]]
Copy after login

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!

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