Several higher-order functions that you must learn to learn Python

1. lambda expression

An anonymous function (English: anonymous function) refers to a class of functions that do not need to define an identifier (function name). In layman's terms, it allows us to function without a function name.

Under normal circumstances, we define a function, using defkeywords, and when you learn to use anonymous functions, alternative defis lambda.

Use here defand lambdaare an example, you will soon understand.

def mySum(x, y):
    return x+y
mySum(2, 3)
# 5

(lambda x, y: x+y)(2, 4)
# 6

From the above example, we can see that the anonymous function runs directly, saving a lot of lines of code. Is there any?

Next, let’s take a closer look at its usage

带 if/else

>>>( lambda x, y: x if x < y else y )( 1, 2 )
1

Nested function

>>>( lambda x: ( lambda y: ( lambda z: x + y + z  )( 1 ) )( 2 ) )( 3 )
6

recursive function

>>> func = lambda n:1 if n == 0 else n * func(n-1)
>>> func(5)
120

or

>>> f = lambda func, n: 1 if n == 0 else n * func( func, n - 1 )
>>> f(f,4)
24

Judging from the above examples, compared with regular functions, lambda expressions have a weird writing style and relatively poor readability. In addition to being able to run directly, it seems that there is no other more prominent function, why do we introduce it today?

First of all, we need to know that lambda is an expression, not a statement. Because of this feature, we can use it in some special scenes. What is the specific scene? Next we will introduce several very useful built-in functions.

2. map function

The map function, it receives two parameters, the first parameter is a function object (of course it can also be a lambda expression), the second parameter is a sequence.

What kind of functions can it achieve? I will give you an example.

>>> map(lambda x: x*2, [1,2,3,4,5])
[2, 4, 6, 8, 10]

It can be clearly seen that it can pass each element in the following sequence as a parameter to the lambda.

When we are not using the map function, you might write like this.

mylist=[]
for i in [1,2,3,4,5]:
    mylist.append(i*2)

3. filter function

The filter function is similar to the map function. It also receives two parameters, a lambda expression and a sequence. It will traverse each element in the subsequent sequence and pass it as a parameter to the lambda expression. When the expression returns True, the element will be retained. When the expression returns False, the element will be discarded.

The following example will filter out a list of elements less than 0.

>>>filter(lambda x: x < 0, range(-5, 5))
[-5, -4, -3, -2, -1]

4. reduce function

The reduce function is similar. Its function is to first operate on the first and second elements in the sequence, and then use the lambda function to calculate the result with the third data, and then calculate the result with the fourth element, and so on. Until there are no more elements.

Here is an example you will understand.

>>>reduce(lambda x,y: x+y, [1,2,3,4,5])
15

The calculation process is broken down like this.

1+2=3
3+3=6
6+4+10
10+5=15

5. Precautions

The above functions, mastering their writing skillfully, can make our code look more Pythonic, and to a certain extent the code looks more concise.

If you are a novice, what you need to pay attention to is that the above example is demonstrated in Python 2.x environment. In Python 3.x, it is different, you can try it yourself.

Here is a summary:

First, what the map and filter functions return is no longer a list, but an iterator object. Here is an example of map

>>> map_obj = map(lambda x: x*2, [1,2,3,4,5])
>>> from collections.abc import Iterator
>>> isinstance(map_obj, Iterator)
True
>>> next(map_obj)
2
>>> list(map_obj)
[4, 6, 8, 10]

The second point is that reduce cannot be called directly, but must be imported before it can be used.

from functools import reduce

Guess you like

Origin blog.csdn.net/weixin_36338224/article/details/109350873