LoginSignup
1
1

More than 3 years have passed since last update.

【Python】イテレータとは

Posted at

以下教材を勉強していく上での備忘録

使用教材:-達人データサイエンティストによる理論と実装- 第3版Python機械学習プログラミング
第6章 6.2.2 k分割交差検証

イテレータとは

Pythonにおけるイテレータとは、リストなどの複数の要素をもったデータ型に対して、順番にデータを取り出す機能のことです。
Python以外の言語では違う使い方をされるようなので注意。

以下具体的なコードにて説明

sample1.py
>>> a = [2, 100, 0.51, "abc", "DEF"] # リストaを定義
>>> i = iter(a) # iter() 関数でリストをイテレータに変換し、変数iにイテレータを代入

>>> next(i) # next()関数が実行される度にリスト内を順番に取り出し
2
>>> next(i)
100
>>> next(i)
0.51
>>> next(i)
'abc'
>>> next(i)
'DEF'
>>> next(i)
Traceback (most recent call last): # 6回目は要素が存在しないため、StopIteration
 File"<stdio>", line 1, in <module>
StopIteration
1
1
0

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
1
1