03: iterators and Generators

Source: Internet
Author: User

* * * iterator (Iterator)

----When you want to return a sequence or a function that executes in a loop, you should consider the generator, which will be passed to another function for subsequent processing, and returning one element at a time can improve overall performance.

The----iterator is simply a container object that implements the iteration protocol, based on two methods: 1) Next (Python 3 is __next__): Returns the next item of the container, and 2) __iter__: Returns the iterator itself. The former returns the next collection element of the iteration , and the latter returns an iterator object (if an object does not have a __iter__ method but defines the __getitem__ method, the object is still iterative).

----Python uses the For or list derivation (list comprehension) to automatically invoke the two methods of next and ITER for you. In the For loop, Python automatically calls the Factory function iter () to get the iterator, automatically calls next () to get the element, and completes the work of checking the stopiteration exception. If you need to call them manually, use Python's built-in function, ITER and next. If C is an iterative object, then you can use ITER (c) to access it, and if a is an iterator object, use Next (a)

Implementation of----iterators

## #1classCount_iterator (object): N=0def __iter__(self):return SelfdefNext (self): y=SELF.N SELF.N+ = 1returnYcounter=Count_iterator ()#Next (counter)## #2classSimpleList (object):def __init__(Self, *items): Self.items=Itemsdef __getitem__(self, i):returnSelf.items[i]a= SimpleList (1, 2, 3) It= ITER (a)#when Python's built-in function Iter will return an iterator type corresponding to this object, and use the __getitem__ method to traverse all elements of the list. If the stopiteration or Indexerror exception is thrown, the iteration stops. #Next (IT)
View Code

--- iter (callable, Flagvalue) iter function A little-known feature is that it takes an optional callable object and a tag (end) value as an input parameter. When used in this way, it creates an iterator that continuously invokes the callable object until the return value and the tag value are equal.   

Generator (Generator)

---- yield applies only to functions. When the generator is called, it returns a value to the caller. Use yield inside the generator to do this. The simplest way to remember what yield actually did is to use it as a special return for the generator function. When you call next (), the generator function continuously executes the statement until yield is encountered, at which point the "state" of the generator function is frozen, the values of all variables are preserved, and the next line of code to be executed is recorded until another call to next () continues to execute the statement after yield. Next () cannot be executed indefinitely, and when the iteration ends, a stopiteration exception is thrown. If you want to end the generator at the end of the iteration, you can use the close () method.

---- It can end with an empty return statement

----Generator function can take parameters

----If I need to access another generator iteration during the iteration of the generator (p3.3 implementation of the delegate generator yield from)

def Frange (Start, Stop, increment):     = start    while x < stop:        yield  x        + = increment  # the generator can only be used for iterative operations, and once the generator function returns to exit, the iteration terminates.   for in Frange (0, 4, 0.5):    print(n)
View Code

----Generator function implementation with external state

#with regard to generators, it is easy to fall into the trap of function omnipotence. If the generator function needs to deal with other parts of your program (such as exposing attribute values, allowing control through method calls, and so on), your code can become unusually complex. If this is the case, consider using the following method to define the class. Defining your generator in the __iter__ () method does not change any of your algorithmic logic. Because it is part of a class, it allows you to define various properties and methods for use by the user.  fromCollectionsImportdequeclasslinehistory:def __init__(Self, lines, histlen=3): Self.lines=Lines Self.history= Deque (maxlen=Histlen)def __iter__(self): forLineno, lineinchEnumerate (Self.lines, 1): Self.history.append ((Lineno, line))yield LinedefClear (self): Self.history.clear ()
View Code

----iterator instead of an infinite loop of while.

03: iterators and Generators

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.