Python: higher-order functions and lambda expressions

Source: Internet
Author: User

Reason:

Python syntax simple to see will, but in practice, think because less than the actual combat, always feel some catch the fly.

Flip through the trace youtube_dl source code, see the filter () function usage, and the lambda expression, feel good interesting, the completion of the class, record the thought.

1. Higher-order functions

The so-called higher order function is the function that can accept the function to do the parameter. Functions that are similar to C # delegates, C + + function pointers, and Delphi events

Like what:

def My_func (F, *args):    f (args)def  My_print (s):    print'  ' liujw ' male '   )

It prints out:

LIUJW, Male

So define the function, it can accept the function to do parameters, and can handle other parameters, we say it is higher-order function.

2. Lambda expression

Lambda expressions return callable function objects and return them at run time, usually in situations where a function is required, but you do not want to name a function.

For example, we define the number addition function:

def Add (x, y):     return x + y

It is represented by a lambda expression as:

Lambda x, y:x + y

It replaces the return statement in the regular Def method with an expression.

Lambda can support 0 to many parameters, but there is no support for variable parameters, namely *args, **args, should not be supported.

3. Built-in high-order functions

3.1 Apply (func[, nkw][, KW]):

Use optional parameters to invoke the func,nkw parameter, the KW keyword parameter, and the return value is the return value of the function call. This function has been discarded in Python 1.6

Purpose: When a function parameter exists in a tuple or a dictionary, it is used to call the function indirectly. Now version Python has allowed direct invocation of functions as parameters, so it has faded out

def my_fun1 ():     Print " My_fun "  def my_fun2 (x, y):     print x + y    apply (MY_FUN1) apply (My_fun2, (3, 5))

The output is:

My_fun8

3.2 Filter (func, seq):

Invokes a Boolean function, Func, to iterate through the elements in each SEQ, returning a sequence of elements that enable Func to return a value of ture.

This is good, I just see it to review its usage, and into this article. In Youtube_dl, a large number is judged as a dictionary class, such as:

Matches = List (filter (lambda f:f['ext') = = ext, formats))

For example, the following code, to find an even number in an array:

LST = [1, 2, 3, 6, 7, 9, ten,, +   ]= filter (lambda x:x% 2 = = 0, lst)print Lst

It returns to:

[2, 6, 10, 12, 18]

3.3 Map (func, seq1[,seq2 ...])

The function func acts on each element of the given sequence (s) and provides the return value with a list, and if Func is none,func as an identity function, returns a list of n tuples containing the set of elements in each sequence.

For example, the above list element is doubled, the writable code is as follows:

LST = [1, 2, 3, 6, 7, 9, ten,, +   ]= map (lambda x:x + x, lst)print LST

The returned result is:

[2, 4, 6, 12, 14, 18, 20, 24, 30, 36]

3.4 Reduce (func, seq[, Init]):

The two-tuple function acts on the elements of the SEQ sequence, each carrying a pair (the previous result and the next sequence element), successively the existing result and the rain to the value of the resulting results, and finally reduce our sequence to a single return value; If Init is given, the first comparison will be init and the first sequence element instead of the first two elements of a sequence.

Python core programming PDF version of the pain of the egg, what is the effect of rain on the value?

Jianfang is the return of Func to the following surface parameters, usually used in mathematical calculations, of course, it is more useful.

For example, the sum of all elements in the list above can be written in the following code:

LST = [1, 2, 3, 6, 7, 9, ten,, +   ]= reduce (lambda x, y:x + y, lst)print re Sult

The result is:

83

3.5 Sorted (iterable, Cmp=none, Key=none, Reverse=false):

As the name implies, it is used for sorting. Accept an incoming parameter, other optional parameters are collation, sort key value, invert, and so on.

If the CMP is empty, the list is sorted by default in ascending order, the CMP return value determines the sort method, >0 is ascending, =0 is unchanged, <0 is descending, and CMP is required to have two parameters.

For example, the following list is arranged in descending order:

LST = [1, 7, 5, 2, 3, 6, 9Lambda x, Y:y- x)print LST

The result is:

[9, 7, 6, 5, 3, 2, 1]

It is the bubble sort method, X is the following element, and y is the preceding element. If arranged in ascending order, X-y is the result.

Reference: Python Core Programming second Edition

Python: higher-order functions and lambda expressions

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.