# 1 迭代器协议

iterator.__iter__()
Return the iterator object itself.

iterator.__next__()
Return the next item from the container.

# 2 可迭代对象

>>> l = [1, 3, 5]
>>> iter(l)
<list_iterator object at 0x101a1d9e8>


# 3 手写一个迭代器

class Odd:
def __init__(self, start=1):
self.cur = start

def __iter__(self):
return self

def __next__(self):
ret_val = self.cur
self.cur += 2
return ret_val


>>> odd = Odd()
>>> odd
<__main__.Odd object at 0x101a1d9b0>


>>> iter(odd)
<__main__.Odd object at 0x101a1d9b0>


>>> next(odd)
1
>>> next(odd)
3
>>> next(odd)
5


odd = Odd()
for v in odd:
print(v)


>>> l = [1, 3, 5]
>>> li = iter(l)
>>> li
<list_iterator object at 0x101a1da90>


>>> next(li)
1
>>> next(li)
3
>>> next(li)
5
>>> next(li)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration


class Odd:
def __init__(self, start=1, end=10):
self.cur = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.cur > self.end:
raise StopIteration
ret_val = self.cur
self.cur += 2
return ret_val


>>> odd = Odd(1, 10)
>>> for v in odd:
...     print(v)
...
1
3
5
7
9


for v in iterable:
print(v)


iterator = iter(iterable)
while True:
try:
v = next(iterator)
print(v)
except StopIteration:
break


# 4 创建迭代器的其它方式

## 4.1 生成器函数

>>> def odd_func(start=1, end=10):
...     for val in range(start, end + 1):
...         if val % 2 == 1:
...             yield val
...
>>> of = odd_func(1, 5)
>>> of
<generator object odd_func at 0x101a14200>
>>> iter(of)
<generator object odd_func at 0x101a14200>
>>> next(of)
1
>>> next(of)
3
>>> next(of)
5
>>> next(of)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration


## 4.2 生成器表达式

>>> g = (v for v in range(1, 5 + 1) if v % 2 == 1)
>>> g
<generator object <genexpr> at 0x101a142b0>
>>> iter(g)
<generator object <genexpr> at 0x101a142b0>
>>> next(g)
1
>>> next(g)
3
>>> next(g)
5
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration


# 5 迭代器的特点

## 5.3 省空间

>>> from sys import getsizeof
>>> a = [1] * 10000
>>> getsizeof(a)
80064


>>> from itertools import repeat
>>> b = repeat(1, times=10000)
>>> getsizeof(b)
56


# 6.2 迭代器遍历完一次就不能从头开始了

>>> l = [1, 3, 5]
>>> li = iter(l)
>>> li
<list_iterator object at 0x101a1da90>
>>> 3 in li
True
>>> 3 in li
False


>>> 3 in l
True
>>> 3 in l
True


# 7 小节

• 实现了迭代器协议的对象都是迭代器
• 实现了 __iter__() 方法并返回迭代器的对象是可迭代对象
• 生成器也是一种迭代器
• 创建迭代器有三种方式，生成器表达式、生成器函数、自定义类，看情况选择最简单的就好
• 迭代器同时也是可迭代对象
• 迭代器是「一次性」的

# 8 参考

posted @ 2019-11-12 00:43  kevinbai_cn  阅读(300)  评论(0编辑  收藏