LoginSignup
0
0

More than 1 year has passed since last update.

【備忘録】PythonのIterator, Generator

Last updated at Posted at 2022-05-04

はじめに

PythonのIteratorに関する備忘録です。

下記の記事を書くためものです。よかったら、こちらも見てみてください。

コード

# generatorの定義、returnではなくyieldであることに注意
def generator():
    i = 0
    while True:
        i = i + 1
        yield  i

threshold = 100

for item in generator():
    print(item)
    if item > threshold:
        break

結果

1
2
3
...
98
99
100
101

プロセスは終了コード 0 で終了しました

説明

PythonのGeneratorは特殊な繰り返し演算子です。 メモリを少なく使うことがメリットです。
yield文を用いて作った場合をGenerator関数、小括弧とlist内包表記を使う場合はGenerator表現と言います。

Generator expression
(x*2 for x in range(256))

List comprehension
[x*2 for x in range(256)]

下記の動画の講義が分かりやすかったので、ご紹介いたします。

0
0
7

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