1
2
3
4
Traceback (most recent calllast):
File "C:/Users/51613/Desktop/Myprogram/协程,迭代器生成器/用法iter()next().py", line 10, in <module>
print(next(i_iter))
StopIteration
迭代器被next调用,超出范围抛StopIteration异常
import time
defgen():
i = 0while i < 4:
yield i
i += 1
g = gen()
print(next(g))
print(next(g))
print(next(g))
print(next(g))
time.sleep(0.5) # 让输出好看点
print(next(g))
结果:
0
1
2
3
Traceback (most recent calllast):
File "C:/Users/51613/Desktop/Myprogram/协程,迭代器生成器/next激活yield.py", line 16, in <module>
print(next(g))
StopIteration
import time
defsend_yield():
i = 0while i < 5:
temp = yield i
print(temp)
i += 1
g = send_yield()
print(g.send(None)) # send之前需要激活。用None激活,或者next()激活。
print(g.send("luo"))
print(g.send("luo"))
print(g.send("luo"))
print(g.send("luo"))
time.sleep(1)
print(g.send("luo"))
结果:
0
luo
1
luo
2
luo
3
luo
4
luo
Traceback (most recent calllast):
File "C:/Users/51613/Desktop/Myfirstprogram/协程,迭代器生成器/send()唤醒生成器yield.py", line 19, in <module>
print(g.send("luo"))
StopIteration