Python Iterator & Builder

Source: Internet
Author: User
Tags generator iterable

Iterators

Any class, as long as it implements the __iter__ method, even if it is an iterative object. The object returned by the __iter__ method of an iterative object is an iterator, and the iterator class needs to implement the next method. In general, the class that implements the __iter__ method must also implement the next method, which means that the class is both an iterative object and an iterator.

An iterator ite can use the Ite.next () method to return its defined next element found in an algorithm, built in ITER (...). function to convert an iterative object into an iterator. The most common use of iterative objects and iterators is the FOR statement:

  For item in iterable this sentence, first calls the __iter__ method of iterable This object, returns an iterator (which in many cases is the Iterable object itself, as stated above, The class of an iterative object tends to implement next to make it its own iterator). According to the algorithm of the next method of the iterator to provide the value one by one, assign this value to item, and then let the item go through the loop body operation.

  If you want to customize an iterator or a class that iterates over an object, you can:

classTest (object):def __init__(self,num=10): Self.num=Num self.li=range (num) self.count=0def __iter__(self):#The general practice is to get __iter__ to return directly to itself.        return SelfdefNext (self):Try:            ifSelf.count = =0:returnSelf.li[0]elifSelf.count <= self.num-1:                returnSelf.li[self.count]Else:                RaiseStopiteration#the statement that invokes the iterator does not know when the iteration will be completed, it is often iterative until the logic given by next continues until an error occurs.
#想让迭代器在某个边际下停止继续迭代的话, you need to raise stopiteration to stop the iteration when appropriate conditions are in place.
#这个raise出来的并不是会输出到stderr的异常或错误, but let the statement that called the iterator know that you can no longer call the next method to get the next value. finally: Self.count+=2#There is also a more tricky, and the iterator itself does not matter the point. Before I wrote count+=2, I found that no matter where I wrote it was not very good.
#因为按照现有语句的逻辑, it is best to add a value of 2 after the next method return, so the next time you enter next, you may not have to return if you exceed the num-1 limit.
# But in general, the statement after return will certainly not be executed in the process of calling the function, except for the try/finally structure.
# that is, the statement in finally will be executed even after the return has been executed. This is more difficult to think of! if __name__=='__main__': Test=Test () forIteminchTest:PrintItem

Generator

Any function with a yield statement is a generator. Yield is usually used in a scenario where, in a (multiple) loop, each iteration of a unit is not processed immediately, but is consolidated and processed together.

When you call a function that has a generator's nature, it returns an iterative object (the normal function returns a real thing if it has a return statement). So you can do it for the item in generator.

Examples are as follows:

defFlatten (nested_thing): forElementinchnetsed_thing:if  notisinstance (element,list):yieldelementElse:             forsubelementinchFlatten (Element):yieldelementnested= [[1,2],[3,4],5,[[6,7],8]]result=list (Flatten (nested))Printresult#the result is [1,2,3,4,5,6,7,8]

The function is to flatten a number of nested lists into a list. You can see that the flatten function is a generator that returns an iterative object (so you can have a for subelement in flatten (element) on recursion). From this example we can also see that in recursion, the yield drop is not divided into the recursive level of uniform placement, so at the first level yield to 5, and the second level (one recursion) yield to 1234, etc. and the third level (two recursion) the yield to everything is put into the same iterative object.

In fact, many times, the generator does not have this necessary (or it seems difficult to understand, so in a simple way?) =) It is possible to use result = [] Before the result is obtained, and then replace the yield statement with result.append (element), and the same result can be obtained.

Python Iterator & Builder

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.