「python」ジェネレータ(generator)のyield文とwhile文を使うサンプル

2020年10月9日

構文
def 関数名():
while 条件
yield xxx

サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# coding: utf-8
def sampleFunc(n):
while n < 10:
yield n
n += 1
res = sampleFunc(0)
print(next(res))
print(next(res))
print(next(res))
print(next(res))
# coding: utf-8 def sampleFunc(n): while n < 10: yield n n += 1 res = sampleFunc(0) print(next(res)) print(next(res)) print(next(res)) print(next(res))
# coding: utf-8

def sampleFunc(n):
      while n < 10:
            yield n
            n += 1

res = sampleFunc(0)

print(next(res)) 
print(next(res)) 
print(next(res)) 
print(next(res))

実行結果
0
1
2
3

Python

Posted by arkgame