迭代器
python迭代器
s = 'hello'
iter_test = s.__iter__()
print(iter_test.__next__())
print(iter_test.__next__())
print(iter_test.__next__())
print(iter_test.__next__())
print(iter_test.__next__())
print(iter_test.__next__())
# for循环使用的是迭代器
for i in s: # s 这一步实际上是执行了迭代器协议转换成了可迭代对象 i_s = s.__iter__() 生成了一个可迭代对象 下一步是 i_s.__next__()
print(i)
s = 'hello'
i_s = s.__iter__()
while True:
try:
print(i_s.__next__()) # 等价于 next(i_s) 内置函数
except StopIteration:
print('迭代完毕, 循环终止')
break
本文标题:迭代器
本文链接:https://www.haomeiwen.com/subject/guhudctx.html
网友评论