iterators and Generators
1. iterators
Iterators are a way to access the elements of a collection. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without going backwards, but that's fine, because people seldom retreat in the middle of an iteration. In addition, one of the great advantages of iterators is that they do not require that all elements in the entire iteration be prepared in advance. An iterator computes an element only when it iterates over it, and before or after that, the element may not exist or be destroyed. This feature makes it ideal for traversing large or infinite collections, such as several G files
Characteristics:
- The visitor does not need to care about the structure inside the iterator, but simply continues to fetch the next content through the next () method
- A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end
- You can't go back halfway through the interview.
- Facilitates recycling of large data sets, saving memory
>>> a = ITER ([1,2,3,4,5]) >>> A<list_iterator object at 0x101402630>>>> a.__next__ () 1 >>> a.__next__ () 2>>> a.__next__ () 3>>> a.__next__ () 4>>> a.__next__ () 5>> > a.__next__ () Traceback (most recent): File "<stdin>", line 1, in <module>stopiteration
2. Generator
When a function call returns an iterator, the function is called the Generator (generator), and if the function contains the yield syntax, the function becomes the generator;
def func (): yield 1 yield 2 yield 3 yield 4
In the code above: Func is a function called a generator, and when you execute this function func () you get an iterator.
>>> temp = func () >>> temp.__next__ () 1>>> temp.__next__ () 2>>> temp.__next__ () 3 >>> temp.__next__ () 4>>> temp.__next__ () Traceback (most recent call last): File "<stdin>", Line 1, in <module>stopiteration
3. Example
A. Use the generator to customize the range
def xrange (n): start = 0 print (start) while True: If Start > N: return yield start Start + = 1obj = xrange (4) n1 = obj.__next__ () N2 = obj.__next__ () n3 = obj.__next__ () N4 = obj.__next__ () N5 = obj.__next__ () N6 = obj.__next__ () print (N1,N2,N3,N4,N5,N6)
B. Using iterators to access range
Python Master's path "Nine" Python-based iterators and generators