What is an iterator?
An iterator is an object used for iterative operations (for loop). It can obtain every element of an iterator like a list.ITERAndNextThe objects of the two methods are all iterators.
Advantages of the iterator
When building the iterator, instead of loading all elements at a time, the next method is called to return elements, so the memory issue does not need to be considered.
Application scenarios of the iterator
- The data scale of the series is huge.
- The number of columns is regular, but cannot be described using list derivation.
Iterator example
In [5]: x = [1, 2, 3] in [6]: Y = ITER (x) in [7]: type (y) out [7]: list_iteratorin [8]: Y. _ ITER _ out [8]: <method-wrapper '_ ITER _' of list_iterator object at 0x0000ee0eb8> in [9]: Y. _ ITER _ () out [9]: <list_iterator at 0x0000ee0eb8> in [10]: Y. _ next _ () out [10]: 1In [11]: Y. _ next _ () out [11]: 2in [12]: Y. _ next _ () out [12]: 3in [13]: Y. _ next _ () Abort stopiteration traceback (most recent call last) <ipython-input-13-2c928e09acf4> in <module> () ----> 1 y. _ next _ () stopiteration: In [14]:
Generator
Generator is an advanced iterator that makes the Code required for functions that need to return a series of elements simpler and more efficient. The computing mechanism of one side is called a generator.
Generator example
# Example 1: Convert the list expression to the generator in [20]: a_list = [x ** 2 for X in range (5)] in [21]: a_listout [21]: [0, 1, 4, 9, 16] in [22]: a_generator = (x ** 2 for X in range (5) in [23]: a_generatorout [23]: <generator object <genexpr> at 0x0000e95830>
# Example 2: Use yieldin [33]: def gen_by_yiels ():...: yield "first "...: yield "second "...: yield "third "...: In [34]: gen_by_yielsout [34]: <function _ main __. gen_by_yiels ()> in [35]: gen_by_yiels () out [35]: <generator object gen_by_yiels at 0x0000f2bf68> in [36]: for X in gen_by_yiels ():...: Print (x )... :... :...: firstsecondthird
References: https://www.zhihu.com/question/20829330
Iterator and Generator