Python 迭代器Iterator详情

1. 什么是迭代器?

  • 迭代器是一个表示数据流的对象,当我们调用next()方法时会返回容器中的下一个值
  • 迭代器中包含
    __iter__
    __next__()
    方法。通过
    __iter__
    方法可以返回迭代器对象本身的方法。
    __next__()
    方法会使cur指针始终指向当前位置,即返回容器中的下一个值,如果容器中没有更多元素了,则会抛出StopIteration异常。
  • 迭代器(iterator)也是可迭代的对象(iterable)

 

2. 迭代器类型

  • Python中支持容器进行迭代,同时也提供迭代器协议支持用户自定义类进行迭代
  • 容器迭代器:
    container.__iter__()
    方法实现容器对象迭代
  • 迭代器协议:
    __iter__()
    方法和
    __next__()
    方法
  • __iter__()
    :返回迭代器本身,容器可以与for...in结合使用
  • __next__()
    :返回迭代器返回下一项

 

3. 迭代器分类

   容器迭代器

data = [1,2,3,4 ]
it
= iter(data) print (next(it)) print (next(it))
  • Python中提供的内置容器有:list、tuple、dictionary 和 set都是可迭代对象
  • 调用iter()方法获取对应的迭代对象
  • 调用next()方法获取迭代对象下一项值。每一次调用next之后,会自动往后移到到一位,获取后面一位的数据。

遍历迭代器

 for  i  in  it:  print (i)

对于可迭代对象,我们也可以使用for...in来进行迭代

 

 自定义迭代器

 

 class  Myiter:  def   __init__  (self,times):
self.times
= times def __iter__ (self):
self.n
= 0 return self def __next__ (self): if self.n <= self.times:
result
= 3 ** self.n
self.n
+= 1 return result else : raise StopIteration
data
= Myiter(4 )
it
= iter(data) # 第1次 print (next(it)) # 第2次 print (next(it)) # 第3次 print (next(it)) # 第4次 print (next(it)) # 第5次 print (next(it)) # 第6次,超出范围触发StopIteration print (next(it))
...
1 3 9 27 81 Traceback (most recent call last):
File
" E:\workspace\uiat\cookbooks\tester.py " , line 67, in <module> print (next(it))
File
" E:\workspace\uiat\cookbooks\tester.py " , line 51, in __next__ raise StopIteration
StopIteration
...

 

  • 创建的对象/类需要实现
    &nbsp;__iter__()
     和 
    __next__()
    两个方法即可作为迭代器
  • 迭代器中__iter__()返回迭代器本身方法
  • 迭代器中__next__()方法允许进行其他操作,但是必须返回迭代器的下一项
  • 为了防止迭代永远进行下去,Python提供stopIterator语句,终止迭代

 

总结

 

Python Iterator迭代器由__iter__()方法和__next__()方法组成。迭代器分为Iterator和iteratable两种,因此迭代器本身也是可迭代对象的。

迭代器分为容器迭代和自定义迭代。

 

标签: python

添加新评论