- 定义:只要可以使用
next
进行元素获取的对象都是迭代器,都可以使用for-in
进行遍历 - 说明:
- 生成器就是一种特殊的迭代器
- 判断是否是迭代器
from collections import Iterator lt = [1, 2, 3, 4, 5] print(isinstance(lt, Iterator)) g = (i for i in range(5)) print(isinstance(g, Iterator))
- 字符串、列表、元组、字典等都不是迭代器,他们都是可迭代对象。
可迭代对象
- 定义:凡是能够使用
for-in
进行遍历的对象 - 说明:
- 前面学习过的字符串、列表、元组、字典等都是可迭代对象
- 判断是否是可迭代对象
from collections import Iterable lt = [1, 2, 3, 4, 5] print(isinstance(lt, Iterable)) g = (i for i in range(5)) print(isinstance(g, Iterable))
- 将可迭代对象转换为迭代器
from collections import Iterator lt = [1, 2, 3, 4, 5] # 将可迭代对象转换为迭代器 lt2 = iter(lt) print(isinstance(lt2, Iterator))
标签: python
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
还木有评论哦,快来抢沙发吧~