1.迭代器
迭代器是一个可以迭代的对象,我们可以通过next()不断取出下一个值,直到抛出StopIteration异常。迭代器的计算是惰性的,只有在需要返回下一个数据时它才会计算。可迭代对象(Iterable)却不一定是迭代器对象(Iterator),这是两个不同的对象,是因为它们实现的方法不一样,后面有说
2.迭代方式
2.1 判断是否可以迭代
from collections.abc import Iterable
d = dict()
print(isinstance(d, Iterable)) # True
print(isinstance(666, Iterable)) # False
2.1 迭代
my_str = "冰冷的希望"
for char in my_str:
print(char)
# 带下标
for index, value in enumerate(my_str):
print(index, value)
3.迭代器对象
3.1 是否迭代器
generator是一个Iterator对象,但python的基本容器类型碎石Iterable对象但不是Iterator,如果想让它们变成Iterator,只需要使用iter()强转一下即可
from collections.abc import Iterator
d = {"a": "1", "b": "2", "c": "3"}
print(isinstance(d, Iterator)) # False
print(isinstance(iter(d), Iterator)) # True
d = iter(d)
print(next(d))
print(next(d))
3.2 迭代对象
可迭代对象与迭代器实现的方法是不同的,我们可以看一下
可迭代对象:实现
__iter__
方法
迭代器对象:实现
__next__
和
__iter__
方法
所以迭代器对象是可迭代对象,但反之不一定
class Fibonacci(object):
def __init__(self, max_count):
self.max_count = max_count
self.cur_count = 0
def __iter__(self):
self.a = 0
self.b = 1
return self
def __next__(self):
if self.cur_count < self.max_count:
self.a, self.b = self.b, self.a + self.b
self.cur_count += 1
return self.a
else:
raise StopIteration
f = Fibonacci(5)
iter(f)
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__next__())