Python basic learning notes (11)

Source: Internet
Author: User

 

 

Iterator

 

This section introduces the iterator. Only one special method is discussed.---- _ ITER __This method is the basis of the iterator rules.

 

Iterator rules

Iteration means repeated operations.---As in the loop._ ITER __Method returns an iterator.NextMethod object.NextMethod, the iterator returns its next value. IfNextThe method is called, but the iterator does not have a value to return.StopiterationException.

 

Here is an example of the number of repeated pona. The iterator is used as follows:

 Class  Fibs:  Def   _ Init __ (Self): Self. = 0 self. B = 1 Def  Next (Self): Self. A, self. B = Self. B, self. A + Self. B  Return  Self.  Def   _ ITER __  (Self ):  Return  Self >>> FABS = Fibs () >>>For F In  Fibs:  If F> 1000 :  Print  F  Break      #  Because break is set, the loop stops here. 1597

Built-in functionsITERYou can obtain the iterator from the iteratable object.

>>> It = ITER ([1, 2, 3])>>>It. Next ()1 >>>It. Next ()2

 

Get the sequence from the iterator

In addition to iterators and iteratable objects, you can also convert them into sequences. In most cases, sequences can be replaced with iterators.

ClassTestiterator: Value=0DefNext (Self): Self. Value+ = 1IfSelf. value> 10:RaiseStopiterationReturnSelf. ValueDef _ ITER __(Self ):ReturnSelf>>> Ti =Testiterator ()>>>List (Ti )[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 

Generator

 

A generator is also called a simple generator. It helps readers write very elegantlyCodeOf course, write anyProgramIt is also possible not to use a generator.

 

Create a generator

Creating a generator is as simple as creating a function.

>>> Def  Flatten (nested ):  For Sublist In  Nested:  For Element In Sublist:  Yield  Element >>> Nested = [[1, 2], [3, 4], [5 ]  #  Use for Loop >>> For Num In  Flatten (nested ):  Print  Num 12345 #  Or use the list function. >>> List (flatten (nested ))[ 1, 2, 3, 4, 5]

 

Recursive Generator

The generator created above can only process two layers of nesting. In order to process nesting, twoForLoop. What if we want to process any layer nesting? For example, you can addForLoop, but do not know how many layers of nesting, so the solution must be more flexible. Now we can solve it with recursion.

>>>DefFLA (AA ):Try:ForBbInAA:ForCCInFLA (bb ):YieldCCExceptTypeerror:YieldAA>>> List (FLA ([[1], 2], 3, 4, [5, [6, 7], 8])#Note that there are many parentheses[1, 2, 3, 4, 5, 6, 7, 8]

WhenFLAThere are two scenarios when called:Basic conditions and situations requiring Recursion

In basic cases, a function is told to expand an element,ForA loop will triggerTypeerrorException. An element is generated.

If a list is expanded, special cases are needed. The program must traverse all the child lists and call them.FLA.

-------------------

The above practice has a problem: IfAAIs an object similar to a string (string,Unicode,Userstring), So it is a sequence and will not triggerTypeerrorBut you do not want to iterate on such objects.

To handle this situation, you must add a check statement at the beginning of the generator. Try to splice the input object with a string to see if it will appearTypeerrorThis is the easiest and quickest way to check whether an object is similar to a string.

>>> Def  Flatten (nested ):  Try  :  # Do not iterate objects similar to strings          Try : Nested + ''          Except Typeerror: Pass          Else : Raise  Typeerror  For Sublist In  Nested:  For Element In  Flatten (sublist ): Yield  Element  Except  Typeerror:  Yield  Nested >>> List (flatten ([ '  Foo  ' ,[ '  Bar  ' ,[ '  Baz  '  ]) [ '  Foo  ' , '  Bar  ' , '  Baz  ' ]

IfNested +''CausedTyperrorIs ignored. If notTypeerror, Then the inner layerTryThe statement will trigger one of its ownTypeerrorException.

 

 

Generator Method

The new property of the generator is the ability to provide values for the generator after it starts running. It is represented by channels through which the generator communicates with the "external world:

* external scope Access Builder send method, just like accessing next the method is the same, except that the former uses a parameter (sent" message " --- Any object)

*The generator is suspended internally,YieldIt is used as an expression instead of a statement. In other words, when the generator is re-running,YieldMethod returns a value, that is, the externalSendThe value sent by the method. IfNextMethod is usedYieldMethod returnNone.

The following is a simple example to illustrate this mechanism:

>>>DefRepeater (value ):WhileTrue: New= (YieldValue)IfNewIs NotNone: value =New>>> R = repeater (42)>>>R. Next ()42 >>> R. Send ("Hello, world!")'Hello, world!'

Two other methods of the generator:

* ThrowMethod (call with the exception type, and optional values and backtracking objects) is used to raise an exception in the generator (inYieldExpression)

* CloseThe method (no parameters are required for calling) is used to stop the generator.

 

 

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.