Python Foundation-16 Generator-Iterator

Keywords: Python

16. Generator-Iterator

_Iterable objects are called iterative objects, and iterator and generator functions are iterative objects. Protocols and methods for defining iterators and generators are provided in Python.

16.1 Iterative and Iterable Objects

16.1.1 Iterable Objects, Iterators, and Iterable Protocols

1. Iterable Objects

_In Python, _u is implementedIter_uThe object of () is an Iterable object.With the built-in function iter(obj), you can call the u of an iterative object objIter_u() method and returns an iterator.Strings, tuples, lists, and so on, are iterative objects, and generator functions and generator expressions are iterative objects.To determine whether an object is iterative, you can use the following:

>>> from collections import abc
>>> isinstance((1,2,3,4),(abc.Iterable,))
>>> isinstance("abcdef",(abc.Iterable,))
>>> isinstance(123,(abc.Iterable,))
>>> isinstance("123",(abc.Iterable,))
>>> isinstance({1,2,3},(abc.Iterable,))
>>> isinstance({"a":1,"b":2},(abc.Iterable,))

2. Iterators

_Realized_uNext_uThe object is an iterator, and the next() built-in function can be used to call the u of the iteratorNext_u() method, returns the next value in turn, and throws an exception StopIteration if there is no value.Iterators enable the iteration cycle of objects, making the program more versatile and efficient.Examples are as follows:

>>> from collections import abc
>>> tempA=(i**2 for i in range(10))
>>> isinstance(tempA,(abc.Iterable,))
>>> tempB={i*2 for i in range(10)}
>>> isinstance(tempB,(abc.Iterable,))

3. Iterator Protocol

_Iterator object must implement two methods_uIter_u() and uNext_u(), these two methods are called iterator protocols. uIter_u() Used to return the object itself for iteration with a loop statement, uNext_u() is used to return the next element.Examples are as follows:

>>> from collections import abc
>>> tempA=(i**2 for i in range(10))
>>> help(tempA)
 |  __iter__(self, /)
 |      Implement iter(self).
 |  __next__(self, /)
 |      Implement next(self).

16.1.2 Iteration of Iterable Objects: iter and next functions

_With the built-in function iter(iterable), you can return iterators for Iterable objects; with the built-in function next(), you can return the next value of the iterator object in turn, and if there is no value, you throw an exception StopIteration.Examples are as follows:

>>> temp=[1,2,3,4] # Iterable Objects
>>> v=iter(temp)   # Getting iterator s from the built-in function iter
>>> next(v)        # Get a value from the built-in function next
>>> next(v)
>>> next(v)
>>> next(v)
>>> next(v)       # When there is no value, an exception StopIteration is thrown
Traceback (most recent call last):
  File "<input>", line 1, in <module>

_In addition to using the next functions, you can use the while loop to iterate over objects as follows:

while True:
    except StopIteration:
    print(value,end=" ")

The results are as follows:

1 2 3 4

16.1.3 Iteration of Iterable Objects: for statement

_In real projects, for statements are often used to iterate over iterative objects.The for loop in Python implements the ability to automatically iterate over Iterable objects as follows:

>>> temp=[1,2,3,4]
>>> for item in temp:
...     print(item,end=" ")
1 2 3 4 
>>> for item in "abcdef":
...     print(item,end="-")

16.2 Custom Iterable Objects and Iterators

_Create a class and define_uIter_u() and uNext_u() Two methods.The object instantiating this class is both an iterator and an iterator.Examples are as follows:

class Fibonacci:

    def __init__(self):

    def __next__(self):
        # f(n)=f(n-1)+f(n-2)
        return self._first
    def __iter__(self):
        return self

for f in fib:
    if f<100:
        print(f,end=" ")

The output is as follows:

1 1 2 3 5 8 13 21 34 55 89

16.3 Generator Function

_In a function definition, if the key yieldstatement is used to return a value instead of return, then a generator function is defined.The generator function uses the yield statement to return a value, then saves the entire execution state of the current function, waiting for the next call.The generator function is an iterator and is an iterative object.Examples are as follows:

>>> def generatorSample(n):
...     for i in range(n):
...         yield i**2
>>> f=generatorSample(5)
>>> f
<generator object generatorSample at 0x00000260CE70E7C8>
>>> item=iter(f)    # Obtaining iterator s from the built-in function iter
>>> next(item)      # Get a value from the built-in function next
>>> next(item)      # Get a value from the built-in function next
>>> for i in f:
...     print(i,end=" ")
4 9 16              # Use the for loop to get the remaining values

_Next, we use the generator to generate Fibonacci columns, and the sample code is as follows:

def Fibonacci():
    while True:
        yield first

for f in Fibonacci():
    if f<100:
        print(f,end=" ")

The output is as follows:

1 1 2 3 5 8 13 21 34 55 89 

16.4 Inverse Iterator: reversed Iterator

_A reverse iterator can be implemented using the built-in function reversed().If an iterative object implements uReversed_u() method, the reversed () function can be used to obtain its inverse iterative object.Examples are as follows:

>>> reversed([1,2,3,4,5])
<list_reverseiterator object at 0x00000260CF0D8908>
>>> for item in reversed([1,2,3,4,5]):
...     print(item,end=" ")
5 4 3 2 1

An example of an iterator that implements a reversible iteration:

class CountSample:

    def __init__(self,startIndex):

    # Forward iteration
    def __iter__(self):
        while n > 0:
            yield n

    # Reverse Iteration
    def __reversed__(self):
        while n<= self._startIndex:
            yield n

if __name__ == '__main__':
    print("Forward iteration")
    for item in obj :
        print(item,end=" ")
    print("\n Reverse Iteration")
    for item in reversed(obj):
        print(item,end=" ")

The output is as follows:

Forward iteration
10 9 8 7 6 5 4 3 2 1
 Reverse Iteration
1 2 3 4 5 6 7 8 9 10

16.5 Generator Expression

_Using generator expressions, you can quickly and easily return a generator.The syntax of the generator expression is basically the same as the list parsing described earlier, except that the generator expression uses () to represent [], which is basically in the following format:

( expr for iterVar in iterable )
( expr for iterVar in iterable if condition)

The expr expression uses iterVar for each iteration to calculate and generate a list.If a conditional expression condition is specified, only the iterable element that meets the condition participates in the iteration.As follows:

>>> (i**2 for i in range(10))
<generator object <genexpr> at 0x00000260CF0B0EC8> # The output indicates that it is a generator
>>> for item in (i**2 for i in range(10)):
...     print(item,end=" ")
0 1 4 9 16 25 36 49 64 81

>>> for item in (i**2 for i in range(10) if i%2==0):
...     print(item,end=" ")
0 4 16 36 64 

16.5 Summary

  • 1. iterable objects: iterable objects are called iterable objects.
  • 2. iterator: implements uIter_u() and uNext_u() object, uIter_uReturns the iterator itself, uNext_uReturns the next value in the iterator and throws a StopIteration exception if there are no elements
  • 3. Generator: A special iterator, defined by the keyword yield, where the generator must be an iterator and vice versa.
  • 4. The diagram of the iteration object and iterator is as follows:

This article address:
This article is published synchronously on the WeChat Subscription Number. If your friends like my article, you can also follow my WeChat Subscription Number: woaitest, or scan the following QR code to add attention:

Posted by kiranoleti on Mon, 01 Jun 2020 09:59:54 -0700