Python high-order functions, anonymous functions

Source: Internet
Author: User

1. Higher-order functions

The higher order function is a function that passes the function as a parameter

Example:

def add (x, Y, f):

return f (x) + f (Y)

Print (Add ( -8, one, ABS))

return Result:

19

①map () function

The map () function receives two parameters, one is a function, the other is a sequence, and map passes the incoming function to each element of the sequence sequentially, returning the result as a new list.

650) this.width=650; "src=" Https://s4.51cto.com/oss/201711/02/b23428b8f3efd26ef3f5484b714cb0c9.png "title=" Clipboard.png "alt=" B23428b8f3efd26ef3f5484b714cb0c9.png "/>

Example:

LST = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def f (x):

return x * x

Map (f, LST)

[1, 4, 9, 16, 25, 36, 49, 64, 81]

Map (str, LST)

[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']

Comments:

Map () The first parameter passed in is F, which is the function object itself


②reduce () function

Reduce functions a function in a sequence [X1, x2, x3 ...] , the function must receive two parameters, and reduce accumulates the result and the next element of the sequence.

Format:

Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1, x2), x3), x4)

#传入的函数必须接受两个参数;

#把可迭代对象的前两个参数作为函数的实参, passed into the F function;

#把每次f运算的结果作为第一个实参, the next element of the object can be iterated as another argument, passed into the function f;

#以此类推 and finally get the result.

Example:

def add (x, y):

return x + y

Reduce (add, [1, 3, 5, 7, 9])

Results:

25


③filter () function

Python's built-in filter () function is used for filtering sequences.

Like map (), filter () also receives a function and a sequence. When different from map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false.

Example 1, in a list, delete an even number, leaving only the odd number:

def is_odd (n):

return n% 2 = = 1

Filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15])

Results:

[1, 5, 9, 15]

Example 2, delete the empty string in a sequence:

def not_empty (s):

return s and S.strip ()

Filter (Not_empty, [' A ', ' ', ' B ', None, ' C ', '])

Results:

[' A ', ' B ', ' C ']


④sorted () function

Sorting algorithms

Sorting is also an algorithm that is often used in programs. Whether you use bubble sorting or fast sorting, the core of the sort is to compare the size of the two elements.

It is generally stipulated that for two elements x and Y, if x < y is considered, then 1 is returned, and if x = = y is considered, then 0 is returned, and if x > y is considered, 1 is returned.

In this way, the sorting algorithm does not care about the specific comparison process, but is directly sorted according to the comparison results.

Python built-in sorted () function

You can sort the list:

Sorted ([36, 5, 12, 9, 21])

[5, 9, 12, 21, 36]

The dict can be sorted:

MM = Dict (A=1, b=2, c=3, d=4)

Print sorted (Mm.itertiems (), key = Lambda d:d[0], reverse = True)


In addition, the sorted () function is also a higher-order function, and it can also receive a comparison function to implement a custom sort.

For example, if you want to sort in reverse order, we can customize a reversed_cmp function:

def reversed_cmp (x, y):

If x > Y:

Return-1

If x < y:

Return 1

return 0

By passing in a custom comparison function reversed_cmp, you can sort in reverse order:

Sorted ([5, 9, reversed_cmp)

[36, 21, 12, 9, 5]

Let's look at another example of string ordering:

Sorted ([' Bob ', ' about ', ' Zoo ', ' credits '])

[' Credits ', ' Zoo ', ' about ', ' Bob ']

By default, the string is sorted by the size of ASCII, and because of ' Z ' < ' a ', the capital letter Z is in front of the lowercase letter A.

Now, we propose that the sort should be ignored in case of alphabetical order.

To implement this algorithm, you do not have to change the existing code, as long as we can define the ignoring case of the comparison algorithm can be:

def cmp_ignore_case (S1, S2):

u1 = S1.upper ()

U2 = S2.upper ()

If U1 < u2:

Return-1

If U1 > U2:

Return 1

return 0

Ignoring the case to compare two strings is actually the first to capitalize the strings (or all lowercase) before comparing them.

In this way, we pass the above comparison function to sorted, and we can implement the sort ignoring case:

Sorted ([' Bob ', ' about ', ' Zoo ', ' credits '], cmp_ignore_case)

Results:

[' About ', ' Bob ', ' credits ', ' Zoo ']

As you can see from the above example, the abstraction of higher-order functions is very powerful, and the core code can be kept very concise.


2. Anonymous functions

As the name implies---> Functions without names

Form 1:

def sum (x, y):

Return X+y

Print (SUM (4, 5))


Form 2:

m = Lambda x,y:x+y

Print (M (4, 5))

Form 1 and Form 2 result as


Supplementary Study website: https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/ 001386819873910807d8c322ca74d269c9f80f747330a52000

This article is from the "Note space" blog, so be sure to keep this source http://286577399.blog.51cto.com/10467610/1978530

Python high-order functions, anonymous functions

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.