📖 preface

You seem to be in a hurry all the time!

Often heard; The teacher tomorrow will you help me to get it, you write for me to finish I learn this time to worry, now this is not no time to learn quickly let me see. In fact, there are many similar to see, very wonder how to your worry, it is not possible, people sit at home, misfortune falls from heaven. The teacher how that time to find you, the boss how to tube you to today, is not accumulated over a long period of time you did not learn, cram in a hurry! Even if someone does help you later, but it is best not to relax, to learn as soon as possible, hide the first day and the second!

Today the blogger is going to talk to you about using Python iterators and generators! Do not like spray, if you have suggestions welcome to supplement, discussion!

For more information on installation and sinification, see this post from the bloggerDownload and Install VsCodeAs well asPython series: windows10 to configure Python3.0 development environment!Restart VsCode after installation!


🚀 last Come on! The iterator

Iteration, one of Python’s most powerful features, is a way to access the elements of a collection. An iterator is an object that remembers where it is traversed. Iterator objects are accessed from the first element of the collection until all elements are accessed. Iterators can only go forward and not back. Iterators have two basic methods: iter() and next(). String, list, or tuple objects can be used to create iterators:

"" @name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. "" list=[1,2,3,4] it = iter(list) # print (next(it)) # print (next(it))Copy the code

Here are the results:

Iterator objects can be traversed using a regular for statement:

"" @name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. List =[1,2,3,4] it = iter(list) # create iterator object for x in it: print (x, end=" ")Copy the code

Here are the results:

You can also use the next() function:

"" @name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. List =[1,2,3,4] it = iter(list) print (next(it)) except StopIteration: sys.exit()Copy the code

Here are the results:


😎 creates an iterator

Using a class as an iterator requires implementing two methods iter() and next() in the class. If you’re familiar with object-oriented programming, you know that every class has a constructor. Python’s constructor is init(), which is executed when the object is initialized. The iter() method returns a special iterator object that implements the next() method and identifies the completion of the iteration with a StopIteration exception. The next() method (next() in Python 2) returns the next iterator object. Create an iterator that returns a number, starting with 1 and incrementing by 1:

"" @param: @return:" "class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 return x myclass = MyNumbers() myiter = iter(myclass) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter))Copy the code

Here are the results:

StopIteration

The StopIteration exception is used to identify the completion of an iteration to prevent an infinite loop. In the next() method, we can set the StopIteration exception to be raised to end the iteration after a specified number of loops have been completed. Stop execution after 20 iterations:

"" @param: @return:" "class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) for x in myiter: print(x)Copy the code

Here are the results:

12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20Copy the code

✨ generator

In Python, a function that uses yield is called a generator. Unlike normal functions, a generator is a function that returns an iterator. It can only be used for iterating operations. It is simpler to understand that a generator is an iterator. When the generator is called to run, the function pauses and saves all current run information each time yield is encountered, returns yield, and continues running from the current position on the next execution of the next() method. Call a generator function and return an iterator object. The following example uses yield to implement Fibonacci sequences:

@param: @return: "" import sys def Fibonacci (n): A, b, counter = 0, 1, 0 while True: if (counter > n): Return yield a a, b = b, a + b counter += 1 f = Fibonacci (10) # f is an iterator that is returned by the generator while True: try: print (next(f), end=" ") except StopIteration: sys.exit()Copy the code

Here are the results:


Here we go :Python iterators and generators! Share finished, go to try it!

🎉 finally

  • For more references, see here:Chen Yongjia’s blog
  • Like the little friend of the blogger can add a concern, point a like oh, continue to update hey hey!