ホームページ  >  記事  >  バックエンド開発  >  効率的な手法でリストをバランスの取れた部分に分割するにはどうすればよいですか?

効率的な手法でリストをバランスの取れた部分に分割するにはどうすればよいですか?

DDD
DDDオリジナル
2024-11-15 12:23:02443ブラウズ

How Can I Split a List into Balanced Parts with an Efficient Technique?

Balancing List Distribution with an Efficient Splitting Technique

In the realm of data manipulation, the ability to evenly distribute a list into multiple parts of desired lengths holds significant importance. This challenge arises in various scenarios, such as when partitioning data for concurrent processing or organizing items into manageable subsets.

One commonly employed approach is the chunks() function, which divides a list into chunks of a specified size. However, this method lacks the precision to create roughly equal parts in all cases. For instance, when splitting a list of 7 elements into 2 parts, it would result in uneven chunks of 3 and 4 elements.

To address this limitation, a more refined solution is presented:

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 approach employs the divmod() function to calculate the number of complete chunks of size k and the number of elements in the remaining partial chunk m. Subsequently, the loop iterates through each chunk, starting from index i, and slices the list to retrieve the desired subset.

As an illustration, consider the following example:

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

In this scenario, the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] is elegantly split into three nearly equal parts, with each chunk containing either 4 or 3 elements.

By incorporating this technique into your programming arsenal, you will gain a powerful tool for managing lists in an efficient and balanced manner.

以上が効率的な手法でリストをバランスの取れた部分に分割するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。