我试图通过构建一个生成器来理解yield语句的行为,该生成器的行为与“枚举”内置函数类似,但我发现根据我如何迭代它而出现不一致。
def enumerate(sequence, start=0):
n = start
for elem in sequence:
print("Before the 'yield' statement in the generator, n = {}".format(n))
yield n, elem
n += 1
print("After the 'yield' statement in the generator, n = {}".format(n))
Run Code Online (Sandbox Code Playgroud)
我对生成器的理解是,一旦到达yield 语句,代码的执行就会停止,并返回一个值。这与我通过下面的脚本得到的结果相匹配。
a = 'foo'
b = enumerate(a)
n1,v1 = next(b)
print('n1 = {}, v1 = {}\n'.format(n1,v1))
n2,v2 = next(b)
print('n2 = {}, v2 = {}'.format(n2,v2))
Run Code Online (Sandbox Code Playgroud)
在这种情况下,生成器似乎完全停止在yield语句处,并在n+=1处用第二个“next”语句恢复:
Before the 'yield' statement in the generator, n = 0
n1 = 0, v1 = f …Run Code Online (Sandbox Code Playgroud)