python--Generator

Source: Internet
Author: User

Generator

First, the concept

The generator in Python (generator) holds the algorithm, and only calculates the value when the desired value is actually called. It is an inert calculation (lazy evaluation).

Ii. List-Generated

Define a list

A = [0,1,2,3,4,5,6,7,8,9]

In addition to the direct definition above, we can also use the list-generated formula:

A = [I for I in Range]]print (a) #输出 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  

Third, generator

With the list generated above, we can create a list directly. However, the capacity of the list is limited by the memory limit. And if we create a list of millions of elements and only need to use the first few elements, then most of the space is wasted.

So, if a list element can be extrapolated by an algorithm, can we continually extrapolate the subsequent elements in the loop? This eliminates the need to create a complete list, which saves a lot of space. In Pyhong, one side loops over the computational mechanism, becoming the generator: generator.

There are many ways to create a generator, and we can directly change the list generation to the generator:

>>> A = (I for I in range) >>> A<generator object <genexpr> at 0x0000024897f6b4c0>

3.1 List generation and generators

A = (I for I in range (100000000)) b = [I-I in range (100000000)]

The generation time of a is instantaneous and does not occupy any memory space. Because the generator does not generate the required content at all, the corresponding value is generated only when it is accessed

3.2 Access Builder

    • The generator retains only the value of the current position, direct access to a[5] is not a value (error)
    • There is only one __next () __ Method
    • Can only be one value, and can only be taken back to the value, cannot return to take the previous value

Use loops to take values:

A = (I for I in range) for I in A:    print (i) #输出0123456789

  

Use the __next () __ method to take a value:

A = (I for I in range) print (a.__next__ ()) print (a.__next__ ()) print (a.__next__ ()) print ("Insert") print (a.__next__ ()) Print (a.__next__ ()) #输出012插入34

Each call to a __next () __ method, we can take a value, and we can only take the value back. The generator can remember the value of the current position, but does not know the value of the front and back position, which is why the generator can save memory. The corresponding data is generated only when it is called to that location.

Iv. yield converts a function into a generator

The use of the list can only achieve a subset of the functionality, a complex operation can not be achieved through the list of generated type. But we can turn a function into a generator.

Fibonacci functions:

def fib (n):    a = 1    b = 1 Number    = 0 while number    < n:        print (b)        B = b,a+b number        + = 1

Turning this function into a generator only needs to change print (b) to yield B

def fib (n):    a = 0    b = 1 Number    = 0 while number    < n:        #print (b)        yield B, a        = b,a+b
   
    number + = 1f = fib (f.__next__) print (f.__next__ ()) print (f.__next__ ()) print (f.__next__ ()) #输出1123
   

  

V. End of generator

Instead of saving the result in a series, the generator saves the state of the generator and returns a value each time it is iterated until the end of the stopiteration exception is encountered.

def fib (n):    a = 0    b = 1 Number    = 0 while number    < n:        #print (b)        yield B, a        = B,a+b        numb ER + = 1    return '--done--' F = fib (6) while True:    try:        x = Next (f)        print (x)    except stopiteration as E :        print (' Generator return value: ', e.value)        break# output 112358Generator return value:--done--

  

python--Generator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.