Python: high-order functions and lambda expressions, pythonlambda

Source: Internet
Author: User

Python: high-order functions and lambda expressions, pythonlambda


The python syntax is simple at a glance, but it is used in NLP. I think it is a bit easy to understand because it is less practical.

Read the source code of youtube_dl and see the usage of the filter () function and the lambda expression in it. If it is interesting, complete the lesson and record it.


1. High-Order Functions

The so-called high-order function is a function that can accept the function as a parameter. Function arguments are similar to c # Delegate, c ++ function pointers, and Delphi events.

For example:

def my_func(f, *args):    f(args)def my_print(s):    print ', '.join(s)my_func(my_print, 'liujw', 'male')

It prints out:

liujw, male

If a function is defined in this way, it can accept the function as a parameter and process other parameters, we will say that it is a high-order function.


2. lambda expressions

Lambda expressions return callable function objects and return them at runtime. They are usually used when a function is needed 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:

lambda x, y: x + y

It replaces the return statement in the conventional def method with an expression.

Lambda supports up to 0 parameters, but does not support variable parameters, that is, * args and ** args, which should not be supported.


3. built-in high-level functions

3.1 apply (func [, nkw] [, kw]):

Optional parameters are used to call func. nkw is a non-Keyword parameter, and kw is a keyword parameter. The return value is the return value of function call. This function has been abandoned in python 1.6.

Purpose: When a function parameter exists in a tuple or dictionary, it is used to indirectly call this function. Currently, python allows you to directly call a function as a parameter, 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))




3.2 filter (func, seq ):

Call a Boolean function func to iterate over the elements in each seq and return a sequence of elements that make the return value of func true.

This is easy to use. I just saw it to review its usage and write it into this article. In youtube_dl, a large number of queries are used as Dictionary classes, such:

matches = list(filter(lambda f: f['ext'] == ext, formats))

For example, the following code calculates the even number in the array:

lst = [1, 2, 3, 6, 7, 9, 10, 12, 15, 18]   lst = filter(lambda x: x % 2 == 0, lst)print lst

It returns:

[2, 6, 10, 12, 18]


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

Function func is used to act on each element of a given sequence (s), and a list is used to provide the return value. If func is None, func is represented as an identity function, returns a list of n tuples containing the collection of elements in each sequence.

For example, if the elements in the list are doubled, the code can be written as follows:

lst = [1, 2, 3, 6, 7, 9, 10, 12, 15, 18]   lst = 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 binary function is used to act on the elements of the seq sequence. Each time a pair (previous result and next sequence element) is carried ), continuously apply the existing results and rain values to the subsequent results, and finally reduce our sequence into a single return value. If the initial value init is given, the first comparison is the init and the first sequence element instead of the first two elements of the sequence.

The translation of Python core programming PDF version is so painful. What is the role of rain?

Simply put, the execution result of the func pair is returned, which is usually used in mathematical calculations.

For example, to find the sum of all elements in the list above, you can write the following code:

lst = [1, 2, 3, 6, 7, 9, 10, 12, 15, 18]   result = reduce(lambda x, y: x + y, lst)print result

The result is:



3.5 sorted (iterable, cmp = None, key = None, reverse = False ):

As the name suggests, it is used for sorting. One input parameter is accepted. Other optional parameters include sorting rules, sorting key values, and whether or not to reverse.

If cmp is empty, the list is sorted in ascending order by default. The values returned by cmp determine the sorting method.> 0 indicates ascending order, and = 0 indicates the same. <0 indicates descending order. cmp must have two parameters.

For example, sort in descending order as follows:

lst = [1, 7, 5, 2, 3, 6, 9]lst = sorted(lst, lambda x, y: y - x)print lst


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

It is a Bubble sorting method, x is the following element, and y is the front element. In ascending order, set x-y as the result.


References: Python core programming Version 2

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: 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.