こんにちは。とむるです。
more-itertoolsのchunkedの使い方について紹介します。
more-itertoolsとは
more-itertoolsは、Pythonの標準ライブラリであるitertoolsを拡張したライブラリになります。pipでインストールすることができます。
1 |
pip install more-itertools |
chunkedとは
今回紹介するchunkedは、more-itertoolsの中のリストなどのiterableを操作するイテレータの1つになります。
chunkedを使うことでiterableを一定の数ごとに分割することができます。
1 2 3 4 |
from more_itertools import chunked l = range(20) print(list(chunked(l, 10))) # [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]] |
1 2 |
print(type(chunked(l, 10))) # <class 'callable_iterator'> |
1 2 3 4 5 6 7 8 9 |
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] chunked_list = list(chunked(l ,2)) for i in chunked_list: print(i) # [1, 2] # [3, 4] # [5, 6] # [7, 8] # [9, 10] |
コメントを残す