Python advanced 06 Loop Object

Source: Internet
Author: User

Vamei Source: Http://www.cnblogs.com/vamei Welcome reprint, Please also keep this statement. Thank you!

The main purpose of this talk is to have a basic concept of looping objects when you are reading a python program.

The Loop object is not with the birth of Python, but it is developing rapidly, especially in the Python 3x era, the cyclic object is becoming the standard form of the cycle.

What is a looping object

The Loop object is an object that contains a next () method (The __next__ () method, in Python 3x), which is intended to proceed to the next result and, after ending a series of results, to cite the stopiteration error.

When a loop structure (for example, for) invokes a loop object, it invokes the next () method every time it loops, until Stopiteration appears, and the For loop receives it, knowing that the loop has ended and stops calling next ().

Let's say we have a Test.txt file:

1234abcdefg

Let's run the python command line:

>>>f = open (' Test.txt ')

>>>f.next ()

>>>f.next ()

...


Continuously enter F.next () until the last occurrence stopiteration

The open () return is actually a loop object that contains the next () method. The next () method returns the contents of the new line each time, and stopiteration is given when the end of the file is reached. In this way, we are the equivalent of a manual loop.

If you do this automatically, it is:

For on open (' Test.txt '):    print Line

Here, the for struct automatically calls the next () method, assigning the return value of the method to line. The loop knows when the stopiteration comes to an end.

The advantage of using a loop object relative to a sequence is that you don't have to create the element you want to use when the loop has not started. The elements used can be generated successively during the loop. This saves space, improves efficiency, and makes programming more flexible.

Iterators

Technically, there is also a middle layer between the loop object and the For loop call, which is to convert the looping object to an iterator (iterator). This conversion is accomplished by using the ITER () function. However, this layer can often be ignored on a logical level, so loop objects and iterators often refer to each other.

Generator

The main purpose of the generator (generator) is to make up a user-defined loop object.

The generator is written in a similar way to the function definition, except that it is changed to yield in the return place. There can be more than one yield in the generator. When the generator encounters a yield, it pauses to run the generator, returning the value after yield. When the generator is called again, it will continue to run from where it was just paused until the next yield. The generator itself forms a circulator that uses a yield return value each time it is cycled.

Here is a generator:

Def gen ():    a =    yield a    a = a*8    yield a    yield 1000

The generator has a total of three yield and three loops when used as a circulator.

For I in Gen ():    Print I

Consider one of the following generators:

Def Gen (): for    I in range (4):        yield I

It can also be written as a generator expression (Generator expressions):

G = (x for x in range (4))

Builder expressions are a simple way to write a generator. The reader may consult further.

Table derivation

Table derivation (list comprehension) is a quick way to generate tables. Its syntax is simple, it has practical value.

Suppose we generate table L:

L = []for x in range:    l.append (x**2)

The above produces the table L, but in fact there is a quick way of writing, that is, table deduction method:

L = [x**2 for x in range (10)]

This is similar to the builder expression, except that it uses the brackets.

(The mechanism of table derivation is actually the use of cyclic objects, which are interested to be consulted.) )

Exercise the following table deduction what will be generated?

XL = [1,3,5]yl = [9,12,13]l  = [x**2 for (x, y) in zip (xl,yl) if y > 10]

Summarize

Looping objects

Generator

Table derivation

Python advanced 06 Loop Object

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.