如何判断一个类的返回对象是否是迭代器
1. 使用 isinstance() 和 collections.abc.Iterator
from collections.abc import Iterator
a = map(lambda x: x**3, [1, 2, 3])
print(isinstance(a, Iterator)) # 输出: True
2.检查迭代器协议的方法
a = map(lambda x: x**3, [1, 2, 3])
print(hasattr(a, '__iter__')) # 输出: True
print(hasattr(a, '__next__')) # 输出: True
# 迭代器的 __iter__ 方法返回自身 print(a.__iter__() is a) # 输出: True
4. 与 Iterable(可迭代对象)的区别
from collections.abc import Iterable, Iterator
a = map(lambda x: x**3, [1, 2, 3])
lst = [1, 2, 3]
print(isinstance(a, Iterable)) # True
print(isinstance(a, Iterator)) # True <- map对象既是可迭代的又是迭代器
print(isinstance(lst, Iterable)) # True
print(isinstance(lst, Iterator)) # False <- 列表是可迭代的但不是迭代器
- Iterable(可迭代对象):可以使用 for 循环遍历的对象,有 __iter__ 方法
- Iterator(迭代器):除了 __iter__ 还有 __next__ 方法,可以逐个产生值
5. 查看文档或源代码
a = map(lambda x: x**3, [1, 2, 3])
print(a.__doc__) # 查看文档字符串
print(help(map)) # 查看map函数的帮助文档
6. 通过行为判断
a = map(lambda x: x**3, [1, 2, 3])
测试是否可以被for循环遍历
for item in a:print(item) # 成功,说明是可迭代的
测试是否可以多次迭代
a = map(lambda x: x**3, [1, 2, 3])list_a = list(a) # 第一次消费list_a2 = list(a) # 第二次消费,得到空列表 []print(list_a2 == []) # True,说明是迭代器(只能消费一次)
对比列表(非迭代器)
lst = [1, 2, 3]
list_lst1 = list(lst) # [1, 2, 3]
list_lst2 = list(lst) # [1, 2, 3]
可以多次迭代a = map(lambda x: x**3, [1, 2, 3])
# 测试是否可以被for循环遍历
for item in a:
print(item) # 成功,说明是可迭代的
# 测试是否可以多次迭代
a = map(lambda x: x**3, [1, 2, 3])
list_a = list(a) # 第一次消费
list_a2 = list(a) # 第二次消费,得到空列表 []
print(list_a2 == []) # True,说明是迭代器(只能消费一次)
# 对比列表(非迭代器)
lst = [1, 2, 3]
list_lst1 = list(lst) # [1, 2, 3]
list_lst2 = list(lst) # [1, 2, 3] 可以多次迭代
7.快速记忆规则 在 Python 3 中,以下内置函数都返回迭代器而不是列表:
map()
filter()
zip()
range() 实际上返回 range 对象,也是可迭代的但不是迭代器
enumerate()
8.使用 iter() 函数测试
python a = map(lambda x: x**3, [1, 2, 3]) print(iter(a) is a) # 输出: True
对于非迭代器的可迭代对象
lst = [1, 2, 3]print(iter(lst) is lst) # 输出: False
查看6道真题和解析