LoginSignup
0
0

More than 3 years have passed since last update.

5-1、イテレータ

Last updated at Posted at 2020-04-29

イテレータ

イタレーションは、リスト、辞書、文字列、タプルなどの要素にアクセスするため、よく使われる機能の1つです。
イテレーションは、最初の要素から最後の要素までを順にアクセスする。(逆走はできない)
イタレーションには2つの基本的な関数がある:iter()とnext()。

>>> data=["a","b","c","d"]
>>> it = iter(data)
>>> print (next(it))  
1
>>> print (next(it))
2
>>>

使い方

普通はfor文を使います。

data=["a","b","c","d"]
it = iter(data) 
for x in it:
    print (x)

もちろん、next()関数も使えます。

import sys  
list=["a","b","c","d"]
it = iter(list)
while True:
    try:
        print (next(it))
    except StopIteration:
        sys.exit()

出力結果は同じく文字列のa,b,c,dとなります。

目次:非IT業種のITメモ

0
0
2

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