current position:Home>Python iterators and generators

Python iterators and generators

2022-01-30 17:46:24 LolitaAnn

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .


Once I was a front-end student, I finally took the postgraduate entrance examination , I thought I got rid of it js, result python There is also an iterator generator , Out of line .


iterator

Usually we use for The cycle is smooth and easy, isn't it . such as

image.png

What's the principle ?

for  Statement is called on the container object  iter(). This function returns a definition  __next__()  Iterator object for method , This method will access the elements in the container one by one . When the elements are exhausted ,__next__()  Will lead to  StopIteration  Exception to notify termination  for  loop . You can use  next()  Built in function to call  __next__()  Method .

Below we see iterator Yes, it is a The list generates an iterator , Every time you call next Will take one a The elements in .

image.png

When you write next When the number of elements is exceeded, there will be StopIteration Abnormal stop .

image.png

generator

With a yield The function of is a generator, It's different from ordinary functions , Generate a generator It looks like a function call , But no function code is executed , Until you call next()( stay for It's called automatically in the loop next()) Just started to execute .

Because I don't learn python Someone who looks directly at the code , I met generator today .

I am here indices There's a whole print(indices), Then call the function in a decent way data_iter(...), The results cannot be printed no matter how they are run or debugged indices, Until I see yield I don't feel good about it …… image.png

Although the execution process still follows the process of the function , But every time it gets to one yield The statement breaks , And return an iteration value , The next execution is from yield Continue with the next statement of . It looks like a function is being yield Several interruptions , Every interrupt passes yield Returns the current iteration value .

yield The benefits are obvious , Rewrite a function to a generator And you get the ability to iterate , Instead of saving the state of a class instance to calculate the next next() Value , Not only is the code concise , And the execution process is extremely clear .

At the end of function execution ,generator Automatically throw out StopIteration abnormal , Indicates that the iteration is complete . stay for In circulation , No need to deal with StopIteration abnormal , The cycle will end normally .

Like a function call , But it's generating a generator :

image.png

yield Action image of return equally , Use next Call generator , Every time the generator executes to yield Throw a return value to stop execution , Until next time next Since the last time yield Continue where you stop , Throw until the iteration object runs out StopIteration Abnormal termination . image.png

Add two small knowledge

  1. How to judge whether a function is generator? If your eyes are OK, you should be able to see yield Of . If you're looking for a way to be tall , That can be used :

    from inspect import isgeneratorfunction 
    isgeneratorfunction( Function name ) 
     Copy code 

    If so, the generator will return true image.png

  2. yield image return, that generator You can have return Do you ?

image.png In a generator function in , without return, The default execution is until the function is finished , If in the course of execution return, And just throw it out StopIteration Termination iteration .

image.png

copyright notice
author[LolitaAnn],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301746206602.html

Random recommended