Python grammar notes (ii)

Source: Internet
Author: User

1. Looping objects

A looping object is a special class of objects that contains a next () method (The __next__ () method in Python3), which is intended to proceed to the next result, and, after a series of results, the stopiteration error is enumerated.

When a loop structure (such as for) invokes the Loop object, it invokes the next () method every time it loops, until Stopiteration appears, and the For loop receives stopiteration, knowing that the loop is over and stop calling next (). For example:

f = open (' 1.txt ') F.next () F.next (). Open () actually returns a loop object, continuously entering F.next () until a stopiteration is encountered using the next () method to loop the object manually, Can be automated: for the Lin in open (' 1.txt ')    print LINEFOR loop structure calls the next () method automatically, assigning the return value of the method to line. The loop knows when the stopiteration comes to an end. The advantage of using a looping object relative to a sequence is that you don't have to create the element you want to use before the loop has started. The elements used can be incrementally generated during the loop, like iterators.

2. iterators

Technically, there is also a middle layer between the loop object and the For loop call, which is to convert the loop object to an iterator. This conversion is achieved through the ITER () function, which is often omitted at the logical level, so the loop-exclusive and iterators often refer to each other.

3. Generator

The builder can construct 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, and when the generator encounters a yield, it pauses the generator and returns 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.

Def gen ():    a =    yield a    a = a*8    yield a    yield 1000for i in Gen. ():    print Idef gen (): For    i I N Range (4):        yield I or can be written as generator expression G = (x for x in range (4))

4. Table derivation

Table derivation is a quick way to generate a table, its syntax is simple, it is practical value.

Suppose we generate table L:

L = []for x in range    ]: l.append (x**2) using a table deduction expression can be easily written as: L = [x**2 for x in range (10)] This is similar to a generator expression, except that you are using brackets.

Note the difference between the generator expression and the table deduction, parentheses vs brackets:

#生成器表达式G = (x for x in range (4)) #表推导L = [x**2 for x in range (10)]

5. Lambda functions

Func = lambda x, y:x+ yprint func (3,4)

A lambda function is an anonymous function that encapsulates some common operating code in your code without requiring an explicit definition of the function.

6. Function as a parameter pass

Functions can be used as an object for parameter passing. The function name is the object, for example:

def test (F, A, B):    print ' Test '    f (A, B) test (func, 3, 4) #func为一个函数, as a parameter, Passed to the function test can also pass a lambda expression as a parameter to the function: Test ((lambda x, y:x**2 + y), 6, 9)

7. Map function

Map () is a python built-in function whose first argument is a function object.

Re = map ((lambda x:x + 3), [1,3,4,5])

Here parameter 1 is the function object defined by lambda, and parameter 2 is a table with multiple elements. The function of map () is to function objects sequentially on each element of the table, and the result of each action is stored in the returned table re. A map is a function that is read into to manipulate the data.

If the function object as a parameter has more than one parameter, you can pass multiple parameters of the function parameter to map () using the following method:

Re = map ((lambda x, y:x + y), [x-ray], [6,7,8])

Map () takes one element from each of the two tables at a time and brings it into the function defined by the lambda.

In Python3, the map () return value is not a table, but a loop object.

8. Filter function

Filter () is similar to map (), which acts as a function object of a parameter on more than one element. If the function object returns True, the elements of the secondary are stored in the returned table. Filter filters the data by a function that is read in. In Python3, filter returns not a table, but a loop object.

def func (a):    if a >:        return True    else:        return falseprint Fileter (func, [10, 56, 101, 100])

9. Reduce function

The first parameter of the reduce function is also a function object, but the function itself can accept two parameters. Reduce can progressively function on individual parameters. Such as:

Print reduce ((lambda x, y:x + y), [1,2,3,4])

The first parameter is a lambda expression that accepts two parameters x, Y, and returns x+y

Reduce passes the first two elements in a table to a lambda function, resulting in 3. The return value 3 will be the first parameter of the lambda function, and the next element 3 in the table as the second parameter of the lambda function, the next call to the lambda function, get 6, and finally get 10. There are no remaining elements in the table.

Python grammar notes (ii)

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.