Home  >  Article  >  Backend Development  >  Analysis of yield and generator in python

Analysis of yield and generator in python

高洛峰
高洛峰Original
2017-03-07 16:38:541317browse

First we import from a small program, define a list each, and find the prime numbers in it. We will write like this

import math
def is_Prims(number):

    if number == 2:
        return True
    //除2以外的所有偶数都不是素数
    elif number % 2 == 0:
        return False
    //如果一个数能被除1和本身之外的数整除,则为合数。其实我们的判定范围到根号n就可以
    for cur in range(2,int(math.sqrt(number))+1,2):
        if number % cur == 0:
            return False
        else:
            return True

def get_Prims(input_list):

    result_list = list()
    for element in input_list:
        if is_Prims(element):
            result_list.append(element)
    return result_list

aa = get_Prims([1,2,3,4,5,6,7,8,9])
print (aa)

But if we want to give a number, and then list the prime numbers larger than this number What about all prime numbers? We might write like this:

def get_Prims(number):    
if is_Prims(number):        
return number

But once the return function hands over control to the caller and ends completely, any local variables and function work are discarded, and the next call will start from scratch. So we can use the following writing method:

def get_Prims(number):
    while(True):
        if is_Prims(number):
            yield number
        number += 1

def get_numbers():
    total = list()
    for next_prim in get_Prims(2):
        if next_prim < 100:
            total.append(next_prim)
        else:
            print(total)
            return

get_numbers()

The generator function is explained below. The def code of a function contains yield, and the function automatically becomes a generator function (even if it still contains return), the generator function creates generator (a special form of iterator, this iterator has a built-in __next__() method). When a value is needed, it is generated through yield instead of direct return. Therefore, unlike ordinary functions, the control right at this time Not handed over.

The for loop will implicitly call the next() function. The next() function is responsible for calling the __next__() method in the generator. At this time, the generator is responsible for returning a value to any method that calls next(). Use Yield passes this value back, which is equivalent to the return statement.

For more articles related to python's yield and generator analysis, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn