如何在Python中將列表分成大致相等的部分?

Mary-Kate Olsen
發布: 2024-11-14 15:03:02
原創
842 人瀏覽過

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))
登入後複製

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.

以上是如何在Python中將列表分成大致相等的部分?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板