Python Advanced tutorials in the Loop object _python

Source: Internet
Author: User
Tags function definition generator in python

The main purpose of this talk is to have a basic concept of the loop object when you read the Python program.

The Loop object does not exist with the birth of Python, but it has developed rapidly, especially in the era of Python 3x, which is becoming the standard form of loops.

What is a Loop object

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

When a loop structure (for example, for) invokes a loop object, it calls the next () method every time it loops, until Stopiteration appears, the for loop receives it, knows that the loop is over, and stops calling next ().

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

Copy Code code as follows:

1234
Abcd
Efg

Let's run the python command line:
Copy Code code as follows:

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

Keep typing f.next () until the last appearance stopiteration

Open () is actually a loop object that contains the next () method. The next () method returns the contents of the new row each time, and the end of the file is stopiteration. In this way, we are equivalent to a manual loop.

Automatically, it is:

Copy Code code as follows:

For line in open (' Test.txt '):
Print Line

Here, the for struct automatically calls the next () method and assigns 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 it is not necessary to generate a good element to use when the loop has not yet begun. The elements that are used can be generated successively during the looping process. This saves space, improves efficiency, and makes programming more flexible.

Iterators

Technically, there is an intermediate layer between the loop object and the for loop call to convert the loop object into an iterator (iterator). This conversion is achieved by using the ITER () function. However, from a logical level, it is often possible to ignore this layer, so that cyclic objects and iterators often refer to each other.

Build device

The primary purpose of the builder (generator) is to form a user-defined loop object.

The generator is written in a similar way as the function definition, except to change the return location to yield. There can be multiple yield in the builder. When the generator encounters a yield, it pauses running the generator, returning the value after yield. When you call the generator again, it will continue to run from where it was paused until the next yield. The generator itself forms a loop that uses a yield return value each time.

The following is a generator:

Copy Code code as follows:

Def gen ():
A = 100
Yield a
A = A*8
Yield a
Yield 1000

The generator has a total of three yield, and if used as a loop, it will be cycled three times.
Copy Code code as follows:

For I in Gen ():
Print I

Consider one of the following generators:

Copy Code code as follows:

Def gen ():
For I in range (4):
Yield I

It can also be written as a builder expression (generator Expression):
Copy Code code as follows:

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

Generator expressions are a simple way to write a builder. Readers may consult further.

Table derivation

Table derivation (list comprehension) is a quick way to generate a table. It has a simple syntax and is of practical value.

Let's say we generate the table L:

Copy Code code as follows:

L = []
For x in range (10):
L.append (x**2)

The above produced a table L, but in fact there is a quick way of writing, that is, table derivation:
Copy Code code as follows:

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

This is similar to the generator expression, except that it is in brackets.

(The mechanism of the table derivation is actually the use of circular objects, which are interesting to refer to.) )

What does the following table deduction generate?

Copy Code code as follows:

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

Summarize

Loop Object
Build device
Table derivation

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.