迭代器作为Python中比较常用的数据类型,Python的官方说明文档给出了迭代器类型的详细说明:本人使用的是Python的3.7.x版本.
原文以及解释
Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods.
Python支持利用容器来实现迭代功能,该功能是用两个方法来实现的,这两个方法允许用户自定义的类支持迭代器。
The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:
方法1,iterator.iter()
Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements.
方法返回迭代器本身,允许容器和迭代器配合 for … in 语句一起使用
方法2,iterator.next()
Return the next item from the container. If there are no further items, raise the StopIteration exception.
返回容器的下一个项,如果容器元素项已经访问完成,抛出StopIteration exception
迭代器使用实例
python 迭代器脚本
class IterList():
def __init__(self):
self.index = 0
self._text = [123, 456, 789, 963, "Nick", "Roly"]
def __iter__(self):
return self
def __next__(self):
if self.index > len(self._text) - 1:
raise StopIteration
self.index += 1
return self._text[self.index-1]
if __name__ == "__main__":
setuter = IterList()
for it in setuter:
print(it)