Get the App
SLTechnology News&Howtos  ›  Development  › 

How to call the python generator

Shulou Source: shulou.com Published: 2022-06-03 15:34:05 11月14日 Update

This article will explain in detail how to call the python generator. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

1. A generator is a function that returns an iterator and can only be used for iterative operations.

2. In the process of calling the generator to run, every time you encounter yield, the function will pause and save all the current running information.

Return the yield value and continue to run from the current location the next time the next () method is executed. Call the generator function to return the iterator object.

Example

Import sys def fibonacci (n): # generator function-Fibonacci a, b, counter = 0,1,0 while True: if (counter > n): return yield an a, b = b, a + b counter + = 1f = fibonacci (10) # f is an iterator Return from the generator to generate while True: try: print (next (f), end= ") except StopIteration: sys.exit () on" how to call the python generator "this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it for more people to see.

Tags: Generation generator function iteration article run more good practical location information content instance object article method knowledge process reference help Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn MariaDB Xiaomi Apple Docker