Basic Python Tutorials (11)

Source: Internet
Author: User
Tags generator


This section makes a discussion of iterators. Only a special method ----__iter__ is discussed, and this method is the basis of the iterator rules.

Iterator rules

Iteration means repeating things many times --- just like you do in a loop. The __iter__ method returns an iterator that is the object that has the next method, and when the next method is called, the iterator returns its next value. If the next method is called, but the iterator has no value to return, a stopiteration exception is thrown .

Here is an example of Gustav, using Iterators as follows:

ClassFibs:Def__init__(self): SELF.A =0 self.b = 1def Next (self): SELF.A, self.b = self.b, SELF.A + self.b return SELF.A def __iter__ (self): return self>>> fibs =  Fibs () >>> for f  In fibs: if F > 1000: Span style= "COLOR: #0000ff" >print f break # Because the break is set, the loop stops here. 1597                 

Built-in function iter can obtain iterators from objects that can be iterated.

>>> it = iter ([2]) >>> () 1>>> ()  

Get a sequence from an iterator

In addition to iterating over iterators and iterative objects, you can convert them to sequences. An iterator can be used to replace most of the cases where the sequence can be used.

Class Testiterator:    value = 0    def Next (self):        self.value + = 1        raisereturn __iter__return self>>> ti = testiterator () >>> list (TI) [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]          




Generators are also known as simple generators, and generators can help readers write very elegant code, but it is also possible to write any program without using a generator.

Creating generators

Creating a generator is as simple as creating a function.

>>>Def flatten (nested): for sublist in nested: for element 
           sublist: yield element >>> nested = [[1,2],[3,4],[5]]# use for loop >>> for num in flatten (nested): print  num 12345# list (flatten (nested)) [1, 2, 3, 4, 5]      

Recursive generators

The generator created above only handles two levels of nesting, and in order to handle nesting using two for loops, if you want to handle nesting of any layer? For example, you might need to add a for loop for each layer nesting, but you don't know how many layers are nested, so you have to make the solution more flexible and can now be solved with recursion.

DEF Fla (aa):    try:        in yield exceptyield# Note the parentheses are more hierarchical than [1, 2, 3, 4, 5 , 6, 7, 8]         


When the FLA is called, there are two things: the basic situation and the case where recursion is required

In the basic case, the function is told to expand an element in which the for Loop throws an TypeError exception that generates an element.

If you are expanding a list, you need special case handling. The program must traverse all the sub-lists and call the fla on them.


There is a problem with the above approach: if AA is a string-like object (String,Unicode, userstring, and so on), then it is a sequence that does not raise TypeError, But you don't want to iterate over such objects.

In order to handle this situation, you must add a check statement at the beginning of the generator. Try stitching the incoming object and a string to see if it will appear TypeError, which is the simplest and fastest way to check whether an object is similar to a string.

>>>DefFlatten (nested):Try:#Do not iterate over objects that resemble stringsTry:nested +‘‘Except TypeError:PassElseRaiseTypeErrorFor sublistInchNestedfor elementInchFlatten (sublist):Yield element except TypeError: yield nested >>> list (flatten ([ ' foo", [ " bar ", [" baz ' ]])) [  "foo",  ' bar",  baz "        

If nested+ ' throws a typerror , it is ignored. If TypeError is not raised , the inner try statement throws a TypeError exception of its own .

Generator method

The new property of the generator is the ability to provide a value to the generator after it has started running. A channel for communication between the generator and the "Outside world":

* External scope access to the generator's send method, just like accessing the next method, except that the former uses a parameter (the "message" Sent--- any object)

* inside the generator is suspended,yield is now used as an expression instead of a statement, in other words, when the generator is newly run, theyield method returns a value, which is the value sent externally by the Send method. If the next method is used, then the yield method returns None.

Here's a simple example to illustrate this mechanism:

def repeater (value): While     True:        new = (yield notnone:value = new >>> r = Repeater>>> () 42>>> r.send ("Hello, world!" )'Hello, world!'              

Another two ways to build the generator:

* Throw method (called with exception type, with optional value and backtracking object) to throw an exception within the generator (in yield expression)

* The close method (without parameters) is used to stop the generator.

Basic Python Tutorials (11)

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: 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.