generator

Understanding Generators in Python

generator内部有yield声明,每次调用next()都会使函数在yield处暂停,并由yield抛出一个返回值。 当函数调用完全之后再次调用next()会报StopIteration错,但如果是使用for循环调用生成器,则会则生成器完全调用之后自动返回

items = [1, 2, 3]
# Get the iterator
it = iter(items) # Invokes items.__iter__()
# Run the iterator
next(it) # Invokes it.__next__()
# 1
next(it)
# 2
next(it)
# 3
next(it)
# Traceback (most recent call last):
#     File "<stdin>", line 1, in <module>
# StopIteration

results matching ""

    No results matching ""