from collections.abc import Iterator def test_yield(n): for i in range(n): yield i * 2 # 暂停在当前步骤, 返回值, 下次继续从暂停位置继续 return -1 my_gen = test_yield(3) print(type(my_gen), isinstance(my_gen, Iterator)) # <class 'generator'> True for elem in my_gen: # 0 2 4 print(elem, end=" ")
while的方式遍历迭代器,通过StopIteration异常来确定是否没有元素了
from collections.abc import Iterator def test_yield(n): for i in range(n): yield i * 2 # 暂停在当前步骤, 返回值, 下次继续从暂停位置继续 return -1 my_gen = test_yield(3) print(type(my_gen), isinstance(my_gen, Iterator)) # <class 'generator'> True while True: try: print(next(my_gen), end=" ") # 0 2 4 except StopIteration as e: print() print(e) # -1 break
多个yield
from collections.abc import Iterator def test_yield(n): for i in range(n): yield i * 2 # 暂停在当前步骤, 返回值, 下次继续从暂停位置继续 yield i * 3 return -1 my_gen = test_yield(3) print(type(my_gen), isinstance(my_gen, Iterator)) # <class 'generator'> True for elem in my_gen: # 0 0 2 3 4 6 print(elem, end=" ")
标签:Iterator,Python,生成器,yield,test,print,my,gen From: https://www.cnblogs.com/sailJs/p/17672870.html