0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python リストをなるべく均等にN分割する

Last updated at Posted at 2022-05-16

はじめに

マルチスレッド(スレッドプール等)で並行処理するときに使えるテクニックです

方法

import random

def split_array(ar, n_group):
    for i_chunk in range(n_group):
        yield ar[i_chunk * len(ar) // n_group:(i_chunk + 1) * len(ar) // n_group]

for _ in range(3):
    # 要素数をランダムに決定
    elem_count = random.randint(100,1000)
    ar = [i for i in range(elem_count)]
    # 分割数をランダムに決定
    n = random.randint(10,20)

    splited = split_array(ar, n)

    print(f'要素数{elem_count}のリストを{n}分割')
    for elem in splited:
        print(len(elem))
結果
要素数416のリストを12分割
34
35
35
34
35
35
34
35
35
34
35
35
要素数921のリストを13分割
70
71
71
71
71
71
70
71
71
71
71
71
71
要素数702のリストを10分割
70
70
70
70
71
70
70
70
70
71
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?