Python3 学习笔记------迭代器

时间:2021-05-22 16:03:31

python 迭代器

要理解python迭代器(iterator),先要理解两个概念:Iterable(可迭代对象)Iterator(迭代器)

先来help()一下Iterator

>>> help(Iterator)
Help on class Iterator in module collections.abc:

class Iterator(Iterable)
 |  Method resolution order:
 |      Iterator
 |      Iterable
 |      builtins.object
 |  
 |  Methods defined here:
 |  
 |  __iter__(self)
 |  
 |  __next__(self)
 |      Return the next item from the iterator. When exhausted, raise StopIteration

发现,Iterator是继承自Iterable,迭代器必须实现__iter__()__next__()

再来看看Iterable:

>>> help(Iterable)
Help on class Iterable in module collections.abc:

class Iterable(builtins.object)
 |  Methods defined here:
 |  
 |  __iter__(self)
 |  

Iterable只定义了__iter__()

现在来说说__iter__()__next__()的作用

1、__iter__() 返回一个迭代器对象

2、__next__()返回迭代器对象的下一个item,如果没有更多的item则raise一个StopIteration异常

来做一个实验

>>> from collections import Iterator, Iterable
>>> l = list('hello world')
>>> isinstance(l, Iterator)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'isinstace' is not defined
>>> isinstance(l, Iterable)
True

从上面的执行结果可以看出,list 对象 l 是 Iterable 而不是 Iterator

>>> next(l)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'list' object is not an iterator
>>> iter_l = iter(l)
>>> for i in range(len(l)+1):
...     next(iter_l)
...     
'h'
'e'
'l'
'l'
'o'
' '
'w'
'o'
'r'
'l'
'd'
Traceback (most recent call last):
  File "<input>", line 2, in <module>
StopIteration

next() 只接受 iterator 作为参数,不接受 iterable。要想用 next() 对 l 进行迭代,要先执行 iter(l) 将 l 转为 iterator