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,))
True
>>> isinstance("abcdef",(abc.Iterable,))
True
>>> isinstance(123,(abc.Iterable,))
False
>>> isinstance("123",(abc.Iterable,))
True
>>> isinstance({1,2,3},(abc.Iterable,))
True
>>> isinstance({"a":1,"b":2},(abc.Iterable,))
True

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,))
True
>>> tempB={i*2 for i in range(10)}
>>> isinstance(tempB,(abc.Iterable,))
True

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
1
>>> next(v)
2
>>> next(v)
3
>>> next(v)
4
>>> next(v)       # When there is no value, an exception StopIteration is thrown
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration

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

temp=[1,2,3,4]
v=iter(temp)
while True:
    try:
        value=next(v)
    except StopIteration:
        break
    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="-")
...     
a-b-c-d-e-f-

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):
        self._first=0
        self._second=1

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

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

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
0
>>> next(item)      # Get a value from the built-in function next
1
>>> 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():
    first,second=0,1
    while True:
        first,second=second,first+second
        yield first

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

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):
        self._startIndex=startIndex

    # Forward iteration
    def __iter__(self):
        n=self._startIndex
        while n > 0:
            yield n
            n-=1

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

if __name__ == '__main__':
    obj=CountSample(10)
    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: https://www.cnblogs.com/surpassme/p/13028211.html
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