Home  >  Article  >  Backend Development  >  Detailed explanation of examples of python iterators

Detailed explanation of examples of python iterators

零下一度
零下一度Original
2017-06-29 10:06:172000browse

The object that can be directly used in the for loop is called iterable object (iterable);

The object that can be called by the next() function and continuously returns the next value is called iterator (iterator);

All iterable objects can be converted into iterators through the built-in function iter().

When using a for loop, the program will automatically call the iterator object of the object to be processed, and then use its next() method until a stoplteration exception is detected.

>>> l = [4,5,6,7,8,9,0]   #这是一个列表
>>> i = iter(l)                 #可迭代对象转换为迭代器;
>>> next(i)
4
>>> next(i)
5
>>> next(i)
6
>>> next(i)
7
>>> next(i)
8
>>> next(i)
9
>>> next(i)
0
>>> next(i)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Because there are no numbers exceeding 0 in the list, when the range exceeds, a StopIteration exception will be returned.

How to judge in a production environment

>>> L = [4,5,6]
>>> I = L.__iter__()
>>> L.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: &#39;list&#39; object has no attribute &#39;__next__&#39;
>>> I.__next__()
4
>>> from collections import Iterator, Iterable
>>> isinstance(L, Iterable)
True
>>> isinstance(L, Iterator)
False
>>> isinstance(I, Iterable)
True
>>> isinstance(I, Iterator)
True
>>> [x**2 for x in I]    
[25, 36]

The above is the detailed content of Detailed explanation of examples of python iterators. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn