LoginSignup
15
11

More than 5 years have passed since last update.

PythonでiterableをN個づつに分割する関数

Last updated at Posted at 2014-09-27

iterableをN個づつに分割してジェネレータにして返します。

コメントで教えていただいたリンクを参考に改良しました。3行まで短くなり無限リストも扱えてウハウハです。
pythonでイテレータをチャンクに分割する

import itertools
def splitparN(iterable, N=3):
    for i, item in itertools.groupby(enumerate(iterable), lambda x: x[0] // N):
        yield (x[1] for x in item)


for x in splitparN(range(12)):
    print(tuple(x))
"""
出力:
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9, 10, 11)
"""

eternal = libs.splitparN(itertools.cycle("hoge"))
print([tuple(next(eternal)) for x in range(4)])
#出力: [('h', 'o', 'g'), ('e', 'h', 'o'), ('g', 'e', 'h'), ('o', 'g', 'e')]

#itertools.chainで元に戻せます
print(tuple(itertools.chain.from_iterable(splitparN(range(12)))))
#出力: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
15
11
5

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
15
11