Yield and Generator of python, pythonyield
First, we will import data from a small program, define a list, and find out the prime number. We will write
Import mathdef is_Prims (number): if number = 2: return True // all the even numbers except 2 are not prime elif number % 2 = 0: return False // If a number can be fully divided by one and itself, it is a combination. In fact, we can determine the range to the root number n for cur in range (2, int (math. sqrt (number) + 1, 2): if number % cur = 0: return False else: return Truedef get_Prims (input_list): result_list = list () for element in input_list: if is_Prims (element): result_list.append (element) return result_listaa = get_Prims ([1, 2, 3, 4, 5, 6, 7, 8, 9]) print (aa)
But what if we want to give a number and list all prime numbers greater than this number? We may write as follows:
def get_Prims(number): if is_Prims(number): return number
However, once the return function gives control to the caller, all local variables and function work will be discarded. The next call will start from the beginning. Therefore, we can use the following code:
def get_Prims(number): while(True): if is_Prims(number): yield number number += 1def get_numbers(): total = list() for next_prim in get_Prims(2): if next_prim < 100: total.append(next_prim) else: print(total) returnget_numbers()
The following explains the generator function. If the def code of a function contains yield, the function automatically becomes a generator function (including return in time ), generator function creates a generator (a special form of iterator, which has a built-in _ next _ () method ), when a value is required, yield is used to generate instead of directly return. Therefore, unlike the general function, the control is not handed over at this time.
The for loop implicitly calls the next () function. The next () function is responsible for calling the _ next _ () method in generator. At this time, the generator is responsible for returning a value to any call to next () yield is used to pass this value back, which is equivalent to the return Statement.
Reference: http://article.yeeyan.org/view/75219/422747