python--iterators, generators, adorners

Source: Internet
Author: User

Iterator iterator rules

Iterations: Repeat things many times, just like in a loop.

Not only can you iterate through dictionaries and sequences, but you can also iterate over other objects: As long as the object implements the __iter__ method.

The __iter__ method returns an iterator (iterator), which is an object that has the next method, which does not require any arguments at the time of the call. When the next method is called, the iterator returns his next value. If the next method is called, but the iterator has no value to return, a Stopiteration exception is thrown.

Note: There are some changes in the iterator rules in 3.0. In the new rule, the iterator object should implement the __next__ method, not next. The new built-in function next method can be used to access this method. In other words, next (IT) is equivalent to It.next () in the previous version of 3.0.

What is the key to iterative rules? Why not use the list? Because the list is too lethal. If you have a function that calculates a value one by one, you might get a value when you use it-instead of getting all the values at once. If there are many values, the list consumes too much memory. But there are other reasons: using Iterators is more general, simpler, and more elegant. Let's take a look at an example that doesn't use a list, because the list length must be infinite.

The "list" here is a Fibonacci sequence. The iterator used is as follows:

classFibs:def __init__(self): SELF.A=0 self.b= 1def __next__(self): SELF.A, self.b= self.b, self.a+self.breturnSELF.Adef __iter__(self):returnSelffibs= Fibs ()#Create a Fibonacci sequence object forFinchFibs#iterate over a sequence of numbers    ifF > 100:        Print(f) Break
using iterators

Note: iterators implement the __iter__ method, which actually returns the iterator itself. In many cases, __iter__ will be placed in other objects that will be used in the For loop. In this way, the program can return the required iterators. In addition, it is recommended to use an iterator to implement its own __iter__ method, and then use the iterator itself directly in the function.

* * Formally speaking, an object that implements the __iter__ method is iterative, and an object that implements the next method is an iterator.

* * Built-in function ITER can obtain iterators from objects that can be iterated. In addition, he can get an iterative object from a function or other callable object.

Get a sequence from an iterator

The

, in addition to iterating over iterators and iterative objects (which is often done), can also convert them to sequences. In most cases where a sequence can be used (except in operations such as indexing or sharding), an iterator (or an iterative object) can be used to replace it. A useful example of this is the use of the list construction method to convert the iterator to a list.

class testiterator:     = 0    def  Next (self):        + = 1        if self.value >:             Raise stopiteration         return Self.value     def __iter__ (self):         return  = testiterator () List (TI)
Generator

The generator is an iterator to a common function definition.

1 defFlatten (nested):2      forSublistinchNested:3          forElementinchsublist:4             yieldelement5 6nested = [[1, 2], [3, 4], [5]]7  forNuminchFlatten (nested):8     Print(num)9 Ten-----Results OneD:\Python27\python.exe d:/pythonwork/day04/iterator.py A1 -2 -3 the4 -5

Any function that contains a yield statement is called a generator. Apart from his name, his behavior differs greatly from ordinary functions. That is, instead of returning a value like return, it produces more than one value at a time. Each time a value is generated (using the yield statement), the function is frozen: that is, the function stops at that point and waits to be woken up again. The function wakes up and executes from the point at which it was stopped.

Recursive generators

Recursion (recursion) is needed to solve the problem of multilayer nested loops. As follows:

1 #solving multiple nested loops problems recursively2 3 4 defFlatten (nested):5     #Handling Exceptions6     Try:7          forSublistinchNested:8              forElementinchFlatten (sublist):9                 yieldElement#using yield yields a value each time, after which the function is frozen and waits for a wake-up. Ten     exceptTypeError: One         yieldNested
Recursive Generator Demo

Resolve the above case:

When flatten is called, there are two possibilities (most of the recursion is handled in two cases): the basic situation and the case where recursion is required. In the basic case, the function is told to expand an element (such as a number). In this case, the for loop throws an TypeError exception (because an attempt is made to iterate over a number), and the generator produces an element.

If you are expanding a list (or other iterative object), special handling is necessary. The program must traverse all the sub-lists (some may not be lists) and call the flatten function on them. Then use another for loop to produce all the elements of the expanded self-list.

* You should not iterate over a string-like object in the flatten function. In two reasons. First of all. You need to implement a string-like object as an atomic value , rather than as a sequence that should be expanded. Second, iterating over them actually leads to infinite recursion, because the first element of the string is another string of length 1, and the first element of the string with length 1 is itself.

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 quickest way to check if an object is not similar to a string. The following code (added to the check statement):

1 defFlatten (nested):2     #Handling Exceptions3     Try:4         Try: Nested +"'5         exceptTypeError:Pass6         Else:RaiseTypeError7          forSublistinchNested:8              forElementinchFlatten (sublist):9                 yieldElement#using yield yields a value each time, after which the function is frozen and waits for a wake-up. Ten     exceptTypeError: One         yieldNested
Demo

To parse the code:

If the expression nested+ ' throws a typeerror, it is ignored. However, if TypeError is not raised, then the ELSE clause in the inner try statement throws a TypeError exception of its own. This will produce a string-like object (outside the EXCEPT clause) as it was.

Generic generator

A generator is a function that contains the yield keyword. When he is called, the code in the body of the function is not executed, and an iterator is returned. Each time a value is requested, the code in the generator executes, knowing that a yield or return statement is encountered. The yield statement thinks that a value should be generated. The return statement means that the generator will stop executing (nothing is generated and the return statement can only be called without arguments if it is used in only one generator).
A generator is a two-bit part: The generator's function and the generator's iterator. The function of the generator is defined by the DEF statement, which contains the portion of yield, and the iterator of the generator is the part returned by this function. The iterator returned by the generator's function can be used in the same way as other iterators.

Generator method

Send method:

The external world scope accesses the generator's send method, just like the next method, except that it uses a parameter (the amount of information to be sent-any object).

Yield method:

Internally, the generator is suspended, yield is now used as an expression instead of a statement, in other words, when the generator is newly run, the yield method returns a value, which is the value sent externally by the Send method.

Attention:

Using the Send method (instead of the next method) only makes sense if the generator is suspended (that is, after the yield function is first executed). If you need to provide more information to the generator before this, you only need to use the parameters of the generator function. For example:

1 defrepeater (value):2      whileTrue:3New = (yieldvalue)4         ifNew is  notNone:5Value =New6 7 8R = Repeater (43)9 Print(R.__next__())Ten Print(R.send ("Hello python!"))
View Code

There are two other ways that the generator

Throw method: Called with exception type, with optional values and backtracking objects to throw an exception within the generator (in the yield expression).

Close method: Used to stop the generator.

Simulation generator

Examples are as follows:

1 #The following is a general function implementation of the flatten generator2 defFlatten (nested):3result = []4     Try:5         #do not iterate over objects that resemble strings6         Try:7Nested +"'8         exceptTypeError:Pass9         Else:RaiseTypeErrorTen          forSublistinchNested: One              forElementinchFlatten (sublist): A result.append (Element) -     exceptTypeError: - result.append (nested) the     returnResult
implementation of common functions for flatten generatorsDecorative Device

See Wu Sir Blog: http://www.cnblogs.com/wupeiqi/articles/4943406.html

  

python--iterators, generators, adorners

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.