Pythonのリストを決まったサイズで分割するときはmore-itertoolsのchunkedを使う

いつも忘れては同じこと調べてるのでメモ。

More Itertools — more-itertools 3.2.0 documentation

pipでインストールして

$ pip install more-itertools

こんな感じで使うと

from more_itertools import chunked

if __name__ == '__main__':
    items = range(28)
    print(list(chunked(items, 10)))

こんな結果になる。

$ python main.py
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27]]

これで忘れても大丈夫。

入門 Python 3

入門 Python 3