. Python Build Builder iterator

Source: Internet
Author: User
Tags iterable

1. Generators and generators

List generation is one of the most popular syntax for Python, and with a simple syntax, you can filter the elements of a tuple and convert the resulting elements.

Syntax format:

[Exp for Val in collection if condition]

Equivalent

result = []

For Val in collection:

if (condition):

Result.append (exp)


Example:

A = [x*x for x in Xrange (ten) if x%2 = = 0]

Print (Type (a))

Print (a)

Results:

<type ' list ' >

[0, 4, 16, 36, 64]

Explain:

① Remove Xrange (10) from 0 to 9

② Judge X*x is an even number, is reserved, exists in the new dictionary

③ all elements that conform to the x*x are returned in the new list.


With the list generation, we can create a list, but, with memory limitations, the list capacity is bound to be limited;

If you create a list of 1 million elements that takes up a lot of storage space, when we just need to access the first few elements, the vast majority of the space behind the elements 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 Python, this side-loop mechanism, called the "generator" (Generator)


A generator is a special type of function that generates a value at a time and can be treated as a recoverable function that returns a generator that can be used to generate a value for successive x;

Simply put, in the execution of the function, the yield statement will return the value you need to the calling generator, and then exit the function, and the next call to the generator function

, the execution starts from where it was last interrupted, and all variable parameters within the generator are saved for the next use.


There are several ways to create a generator:

The first of these methods

Convert a list-generated [] to (), which creates a generator.

Example:

LST = (x*x for x in Xrange (1,101) If x%2 = = 0)

Print (LST)

Print (Type (LST))

Print (Lst.next ())

Print (Lst.next ())

Print (Lst.next ())

Print (Lst.next ())

Print (Lst.next ())

Print (Lst.next ())

Results:

<generator Object <genexpr> at 0x02e72508>

<type 'generator' >

4

16

36

64

100

144


Explain:

Generator saves the algorithm, each time it calls next (), calculates the value of the next element until it is calculated to the last element.


The second method:

The function defines the list generator, that is, if the function contains the yield keyword, then the function is no longer a normal function, but a generator.


Common functions:

def func (N):

sum = 0

i = 0

while (I<n):

sum = sum + I

i + = 1

Print (sum)

Func (10)

Results:

0

1

3

6

10

15

21st

28

36

45


List Builder:

def func (N):

sum = 0

i = 0

while (I<n):

sum = sum + I

i + = 1

Yield (sum)

For X in Func (10):

Print X

Print (Type (func (10)))


Results:

0

1

3

6

10

15

21st

28

36

45


Explain:

① above function has the keyword yield, so the generated is a generator;

② calls the generator through a for loop, and when executed to yield, returns the sum value, sum of 0, at which time the value of sum is paused and recorded;

③ prints out the value of sum, and then continues to execute, jumping into the next loop while (1<10)

④ returns the value of sum until yield is encountered

⑤ repeatedly executes the 3,4 steps until the loop ends and eventually exits the program.


The difference between the two functions:

One directly returns 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 output directly through a loop.

The generator does not list all the data at once, and when you use it, it is listed again, saving more memory usage.


Common functions and List Builder differences:

The result is the same, but the function that contains the yield statement is specifically compiled into the generator, and when the function is called, they return a generator object that supports the iterator interface,

Whenever the yield keyword is encountered, it can be understood as the return statement of the function, and the value after yield is the returned value. But unlike a normal function that exits after a return, the generator function generates

Values will automatically suspend and pause their execution and state, and his local variables will hold the state information, which will be valid again when the function resumes, and is executed next time from the section below yield.

For example, the last time you execute to 3, the next time you start, you'll find 3 locations, starting with 6, (not starting from scratch), and so on.


Supplementary study: http://www.jianshu.com/p/d09778f4e055

Generated: All data is generated at once and then stored in memory for small amounts of data.

Generator: Returns an iterative object, the "Generator" object, which must be looped to list all the results.


2. iterators

The main differences between iterable (iterative objects) and iterator (iterators) are:

Anything that can be used for a loop is iterable (an iterative object) that can be called by loop, such as: [], (), {}, generative ....

An iterative object that is called by the next () function and gets the value is iterator (iterator)

So the object that the generator can be called by the next () function and constantly returns the next value is called an iterator.

It is simple to understand that a generator is an iterative object of iterators.


All objects that can be used for a for loop are iterable classes

All objects that can be used for the next () function are iterator types, which represent a sequence of lazy computations.



Homework:

99 Multiplication Table

def func (N):

return ["{0}*{1}={2}". Format (X,n,x*n) for x in Xrange (1,n+1)]


For I in Xrange (1,10):

Print "". Join (func (i))


This article is from the "Note space" blog, so be sure to keep this source http://286577399.blog.51cto.com/10467610/1978911

. Python Build Builder iterator

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.