参考:
https://www.programiz.com/python-programming/iterator
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143178254193589df9c612d2449618ea460e7a672a366000
-
一个迭代器是可以用next方法调用的。也可以用__next__()
也可用for循环。
实际for循环的使用,是先转为迭代器的。 -
generator,包括生成器(括号形式的列表生产式,)、带yield的generator function.
-
list,tuple,dict,str等是可迭代对象,要转换为迭代器,需要用 iter()
-
构建自己的 迭代器,要实现__iter()__、__next()__以及StopIteration等:
### 似乎用 **generator function**会简单很多!!!
class PowTwo:
"""Class to implement an iterator
of powers of two"""
def __init__(self, max = 0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
result = 2 ** self.n
self.n += 1
return result
else:
raise StopIteration
------------------
>>> a = PowTwo(4)
>>> i = iter(a)
>>> next(i)
1
>>> next(i)
2
>>> next(i)
4
>>> next(i)
8
>>> next(i)
16
>>> next(i)
Traceback (most recent call last):
...
StopIteration
-------------------------------------------------------
>>> for i in PowTwo(5):
... print(i)
...
1
2
4
8
16
32