iterator

iterator:

      We already know that the data types that can be directly applied to the forloop are as follows:

       One is a collection data type, such as list, tuple, dict, set, stretc.;

       One class is the generator function generatorthat includes generators and bands .yield

      These objects that can act directly on forloops are collectively called iterable objects: Iterable.

       You can use to isinstance()determine whether an object is an Iterableobject:

 

>>>  from  collections  import  Iterable
>>>  isinstance ([], Iterable)
True
>>>  isinstance ({}, Iterable)
True
>>>  isinstance ( 'abc' , Iterable)
True
>>>  isinstance ((x  for  in  range ( 10 )), Iterable)
True
>>>  isinstance ( 100 , Iterable)
False

The generator can not only act on the forloop, but also can be next()continuously called by the function and return the next value, until StopIterationan error is thrown at the end, indicating that the next value cannot be returned.

* Objects that can be called by next()a function and keep returning the next value are called iterators:Iterator .

You can use to isinstance()determine whether an object is an Iteratorobject:

 

 

 

Generators are Iteratorobjects, but list, dict, stralthough they are Iterable, but they are not Iterator.

Turn list, dict, stretc Iterableinto Iteratorusable iter()functions:

 

You might ask, why are list, dict, , stretc. data types not Iterator?

This is because Python Iteratorobjects represent a stream of data, and the Iterator object can be called by next()a function and keep returning the next data until StopIterationan error is thrown when there is no data. This data stream can be regarded as an ordered sequence, but we cannot know the length of the sequence in advance, and can only continuously next()calculate the next data on demand through the function, so Iteratorthe calculation is lazy, only when the next data needs to be returned it will only be calculated.

IteratorIt can even represent an infinite data stream, such as all natural numbers. And using list is never possible to store all natural numbers.

 

summary

Any forobject that can act on a loop is a Iterabletype;

All objects that can act on next()functions are Iteratortypes, and they represent a lazily computed sequence;

Collection data types such as list, dict, stretc. are Iterablebut not Iterator, but iter()an object can be obtained through a function Iterator.

Python's forloops are essentially next()implemented by constantly calling functions, for example:

for in [12345]:

     pass

 

# First get the Iterator object:
it = iter([1, 2, 3, 4, 5])
# Loop:
while True:
    try:
        # Get the next value:
        x = next(it)
    except StopIteration:
        # Exit the loop when StopIteration is encountered
        break

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324745641&siteId=291194637