by shigemk2

当面は技術的なことしか書かない

エキスパートPythonプログラミング ウィンドウイテレータ

isliceはシーケンスのサブグループに対するイテレータを返す。
次の例は、標準入力から行単位で入力を読み込み、その行が5つ以上の要素を
持つ場合に5番目の要素から順にyieldする

Python 2.7.4 (default, Apr 18 2013, 22:40:51)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import itertools
>>> def starting_at_five():
...     value = raw_input().strip()
...     while value != '':
...         for el in itertools.islice(value.split(), 4, None):
...             yield el
...         value = raw_input().strip()
...
>>> iter = starting_at_five()
>>> next(iter)
one two three four five six
'five'
>>> next(iter)
'six'
>>> next(iter)
one two
one two three four five six
'five'
>>> next(iter)
'six'
>>> next(iter)
one
one two three four five six seven eight
'five'
>>> next(iter)
'six'
>>> next(iter)
'seven'
>>> next(iter)
'eight'
>>> next(iter)