Python: Generator

Source: Internet
Author: User
Tags for in range function definition generator

Generator #生成器

    • Can iterate
    • Can only be read once
    • Generate data in real time, not all in memory

With a list build, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted. If a list element can be inferred from an algorithm, can we continually extrapolate the subsequent elements in the process of looping? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.

# the 11th way to create a generator is as simple as changing a list-generated [] to (), creating a generator:  for  in range () >>> 1, 4, 9, +, (+), +, +, Bayi]for in Range (Ten)>>> g<generator object <genexpr> at 0x1022ef630># The difference between creating L and G is only the outermost [] and (), L is a list, and G is a generator. 

#If you want to print one, you can get the next return value for generator by using the next () function:>>>Next (g) 0>>>Next (g)1>>>Next (g)4>>>Next (g)9>>>Next (g)16>>>Next (g)25>>>Next (g)36>>>Next (g)49>>>Next (g)64>>>Next (g)81>>>Next (g) Traceback (most recent): File"<stdin>", Line 1,inch<module>stopiteration#but the constant call to next (g) is so perverted that the correct approach is to use a For loop because generator is also an iterative object:>>> g = (x * x forXinchRange (10))>>> forNinchg: ...Print(n) ... 0149162536496481

Yield keyword

use generator to implement the FIB sequence as an example: Fibonacci Sequence (Fibonacci): Any number except the first and second numbers can be added by the first two numbers.

1, 1, 2, 3, 5, 8, 13, 21, 34, ...

# The Fibonacci sequence is not written with a list, and it is printed with a function first: def fib (max):     = 0, 0, 1 while     n < Max:        print(b)        = B, A + b        = n + 1 # Call >>> fib (6)112358

fibThe function is actually the extrapolation rule that defines the Fibonacci sequence, starting with the first element and extrapolating any subsequent elements, which are actually very similar to generator.

In other words, the above functions and generator are only a step away. To turn fib a function into a generator, just print(b) change yield b it to:

deffib (max): N, a, b= 0, 0, 1 whileN <Max:yieldb A, b= B, A +B N= n + 1return ' Done'#This is another way to define generator. If a function definition contains the yield keyword, then the function is no longer a normal function, but a generator:>>> f = fib (6)>>>F<generator Object fib at 0x104feaaa0>#Similarly, after changing a function to generator, we basically never use next () to get the next return value, but instead use the For loop to iterate:>>> forNinchFIB (6):...     Print(n) ...112358#However, when you call generator with a For loop, you find that you cannot get the return value of the generator return statement. If you want to get the return value, you must catch the Stopiteration error, and the return value is contained in the value of Stopiteration:>>> g = fib (6)>>> whileTrue: ...Try: ... x=Next (g) ...Print('g:', x) ...exceptstopiteration as E: ...Print('Generator return value:', E.value) ... Break... g:1g:1g:2g:3g:5g:8GeneratorreturnValue:done

A better implementation of the Fibonacci sequence:

#Defining implementation Functionsdeffib (n):ifN <= 1:        returnNElse:return(FIB (n-1) + fib (n-2))#Get user Inputnum = Int (input ("How many items do you want to output?"))#Check that the numbers you entered are correctifNum <=0:Print("Enter a positive number")Else:    Print("Fibonacci Sequence:")     forIinchrange (num):Print(Fib (i))
# output How many items do you want to output? Fibonacci Series: 0112358132134

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.