pythonのイテレータとイテラブルについて enumerate()のドキュメントを参照した際の備忘録
イテレータとイテラブルとは
イテラブルとは反復可能であるということ。 イテレータはnextメソッドを持つ。 イテレータは、処理の状態をもっている。よって順番に取り出すときにリストより便利な場合がある。
enumerate()
ドキュメント参照
enumerate(iterable, start=0) Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
seasons = ['Spring', 'Summer', 'Fall', 'Winter'] list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
next(seasons)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-a76fcce3fb20> in <module>()
----> 1 next(seasons)
TypeError: 'list' object is not an iterator
iter()
iter()によってコンテナをイテレータにすることができる。
seasons_iter = iter(seasons) next(seasons_iter)
'Spring'
next(seasons_iter)
'Summer'
next(seasons_iter)
'Fall'
next(seasons_iter)
'Winter'
next(seasons_iter)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-20-f2e6da853580> in <module>()
----> 1 next(seasons_iter)
StopIteration:
参照元
http://www.bokupy.com/detail/29
https://docs.python.jp/3/library/functions.html#enumerate