[python]--iterator, Generator supplement

Source: Internet
Author: User
Tags iterable

In Python, List,string,dict is an iterative object that can be traversed by a for statement.

Iterators

The iterator object requires an object that supports the iterator protocol, and in Python, the __iter__ () and Next () methods of the object are implemented even though the iterator protocol is supported. where the __ITER__ () method returns the Iterator object itself;

The next () method returns the next element of the container, throwing an stopiteration exception at the end

__iter__ () and Next () methods

These two methods are the most basic method of iterators, one to get the iterator object, and one to get the next element in the container.

For an iterative object, you can use the built-in function iter () to get its iterator object:

  

The ITER () method can obtain an iterator object for the list and then use the __next__ () method to access the elements in the list. When there are no accessible elements in the container, the __next__ () method throws a

Stopiteration an abnormally terminated iterator.

If you do not use the ITER () method, you can use the next () method to iterate over an object to get the next element

Custom iterators

Once you understand the iterator protocol, you can customize the iterator.

The following example implements a myrange type, which implements the __iter__ () method, which returns the object itself as an iterator object, and implements the next () method to get the next element in the container, when there is no accessible element. Throws a Stopiteration exception.

    

classMyRange (object):def __init__(self, N): Self.idx=0 SELF.N=Ndef __iter__(self):return SelfdefNext (self):ifSelf.idx <Self.n:val=Self.idx Self.idx+ = 1returnValElse:            RaiseStopiteration ()

This custom type is similar to the built-in function xrange, and looks at the results of the operation:

    

Generator

In Python, it is convenient to use the builder to support the iterator protocol. The generator is generated by a generator function, which can be defined by a regular DEF statement, but instead of return, it returns one result at a time with yield, suspending and continuing their state between each result. To automatically implement an iterative protocol.

In other words, yield is a syntactic sugar. The internal implementation supports the iterator protocol, while the yield internally is a state machine that maintains the status of suspend and continue.

Here's how the generator is used:

  

In this example, a generator function is defined, and the function returns a generator object, which can then be iterated through the for statement.

In fact, the generator function returns an iterator to the generator, and the term "generator iterator" is often referred to as the "generator." Note that the generator is a special kind of iterator. As an iterator, the generator must define methods, one of which is next (). Like an iterator, We can use the next () function to get the next value.

  Generator execution Process

    • When the generator function is called, the function simply returns a generator object and does not execute.
    • When the next () method is called for the first time, the generator function begins execution, and execution stops at the yield statement
      • The return value of the next () method is the argument at the yield statement (yielded value)
    • When the next () method continues to be called, the function continues at the last stop yield statement and stops at the next yield and throws a stopiteration exception if no yield is followed

Builder expression

Before we begin to introduce the builder expression, let's look at our familiar list comprehensions, which is usually the following form of list parsing.

[Expr for Iter_var in iterable if cond_expr]

Iterate over all the contents of the iterable, after each iteration, put the contents of the iterable satisfies the cond_expr condition into the Iter_var, then the content that should be iter_var in the expression expr, and finally live a list with the computed value of the expression.

For example, generate a list to hold all the odd numbers within 50:

[I for I in range () if i%2]

The generator expression is introduced in python2.4, and you should consider using a generator expression instead of a list resolution when the sequence is too long and you need to get only one element at a time. The syntax of a generator expression is just like a list resolution, except that the generator expression is surrounded by (), not [], as follows:

(Expr for Iter_var in iterable if cond_expr)

The generator expression does not create a list, but instead returns a generator that, after each calculation of an entry, "yields" the entry, the generator expression uses lazy computation and is only assigned when retrieved, so it is more efficient to use memory when the list is longer

The builder expression produces a generator that itself is an iterative object and is also the iterator itself

  Recursive generators

The generator can be used recursively like a function, and here's a simple example of a sequence that is fully arranged:

  

defpermutations (LI):ifLen (li) = =0:yieldLiElse:         forIinchRange (len (LI)): Li[0], Li[i]=Li[i], li[0] forIteminchPermutations (li[1:]):                yield[Li[0]] +Item forIteminchPermutations (Range (3)):    PrintItem

Generator's send () and close () methods

There are two other important methods in the generator: Send () and close ()

Send (value):

From the previous understanding, the next () method can restore the generator State and continue execution, in fact, send () is a method other than next () recovery generator.

In python2.5, the yield statement becomes the yield expression, which means that yield can have a value, and this value is the parameter of the Send () method, so Send (None) and next () are equivalent. Again, next () and send () The return value is the argument at the yield statement

About Send (): The generator must be in a pending state before calling send to pass in a value other than none, or an exception will be thrown

Close ():

This method is used to close the generator, and calling next or send will throw an exception when the generator is closed

  

[python]--iterator, Generator supplement

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.