(iii) 3-5 Python build and generator

Source: Internet
Author: User
Tags function definition generator generator iterable save file

Generators and generators

List generation is one of the most popular syntaxes of Python, with indirect syntax for filtering a set of elements and processing elements in the form of [exp for Val in collection if condition]
Equivalent:

result = [] for in collection:    if  (collection):        Result.append (exp)

For example:

 for inch if x*x%2 = =0]print(type (a))print(a)

Operation Result:

<type ' list ' >
[0, 4, 16, 36, 64]

Note: 1, take out the number of xrange (10) from 0 to 9
2, Judge X*x is an even number, keep existing in the new list
3. Put all elements that match x*x to the new list and return
Use the normal function to implement:

def Fun ():     = []    for in xrange (1,10):        if x%2 = = 0:            list.append (x *x)    returnprint(Fun ())

There are a number of ways to create a producer, and the first is to change a list-generated [] to () and create a generator

 for inch if  x%2 = =0)print(LT)print(LT) for in LT:    print(i)

Operation Result:

<generator Object <genexpr> at 0x00000000025cdd80>4163664

Note: Gengerator saves the algorithm, each time it calls next (), calculates the value of the next element, until the last element is calculated.
The generator is a special function that generates a value at a time, calling the function to return a generator generator that can be used to generate successive X-values, and during the execution of the function, the yield statement returns the required value to the calling generator, and then exits the function. The next call to the generator function is executed from the point where it was last interrupted, and all parameters that are generated will be saved for the next use.

The second method: If a function definition contains the yield keyword, then the function is no longer a normal function, but a generator
Before we get into this approach, let's look at an example

def fib (n):     = 0    = 0    while (i<N):        +=        I+=1        Print  (sum) fib (5)

Operation Result:

0
1
3
6
10

Using yield can be rewritten as:

def fib (n):     = 0    = 0    while (i<N):        +=        I+=1        yield  sum for in fib (5):    Print(x)  Print(Type (FIB (5)))

Operation Result:

0
1
3
6
10
<type ' Generator ' >

As a result of the above 2 methods, the function containing the yield statement is specially compiled into the generator, and when the function is called, they return a generator object that supports the iterator interface, and whenever the yield keyword is encountered, the return statement of the function, the value after yield is the value returned. However, unlike normal functions that exit after return, the generator functions automatically suspend and pause their execution and state after the value is generated, and once again, when the function resumes, the next part of yield starts executing.


The difference between a generator and a build
The difference between the two: a direct return to the result list of the expression, and the other is an object that contains a computed reference to the result of the expression, which can be directly output through a loop
The generator doesn't list all the data at once, and when you use it, it's more memory-efficient when it's listed.
Generated: All data is generated at once and then stored in memory for small amounts of data
Generator: Returns an object that can be iterated, and an "generator" object that must be looped to make sense of all the results
An iterative object: A loop can be called to iterate over an object.

Iterators
The main differences between iterable (iterative objects) and iterator (iterators) are:
All that can be used for loops are iterable (iterative objects)
An iterative object that needs to get a value through the next () function is a iterator (iterator)
A generator is an iterative object of iterators

——————————————————————————————————————————————————

Exercise: Using functions to implement 9*9 multiplication formulas

#!/usr/bin/env python#Coding:utf8ImportCodecsdefWrite_file (res): With Codecs.open ("9_9.txt","AB") as Fd:fd.write (res)defget_9_9 (): forIinchRange (1,10):        #print (i)         forJinchRange (1,i+1):            Print  "{0} * {1} = {2}". Format (j,i,i*j), Res="{0} * {1} = {2}". Format (J, I, I *j)#Print ResWrite_file ("{0}". Format (res))PrintWrite_file ("\ n")if __name__=="__main__": Get_9_9 ()

Operation Result:

Save File 9_9.txt content:

(iii) 3-5 Python build and generator

Related Article

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.