Are you sure you don't know about python anonymous functions anymore?

The previous chapter described custom functions, while anonymous functions are a special case of custom functions. It only needs one line to define functions and has a cool name 'lambda'

1, Foundation

# definition
lambda arg1,arg2,arg3,...argn:expression

# For example, the previously defined my_sum function
def my_sum(num1, num2):
    return num1+num2
# lambda expressions 
mysum = lambda x,y: x+y
# 5

# It can be seen that lambda is actually a function object returned, and its usage is the same as that of normal methods
  • The difference between lambda expression and normal function
    • lambda is an expression, not a statement
      • Expression: use a series of "formulas" to express a thing, such as x + 2, x*2, etc
      • Statement: it must have completed some functions, such as assignment statement x=1, assignment, print statement printing, if judgment, etc
# Since lambda is an expression, it can be used where some custom conventional functions cannot be used

# For example, lambda can be used inside a list
[(lambda x:x+2)(x) for x in range(5)]
#Output: [2, 3, 4, 5, 6]

# For example, as parameters of some functions
l = [(1,2),(5,7),(3,4)]
l.sort(key = lambda x:x[1])
#[(1, 2), (3, 4), (5, 7)]

# Ordinary functions can only be called by function name, so they must be defined first,
# As an expression, lambda can directly return function objects as expressions
  • The main body of lambda is a simple expression with only one line, which cannot be extended into a multi line code block

    This is mainly due to design considerations, so that it and custom regular functions perform their respective duties: lambda focuses on simple tasks, and custom regular functions are responsible for more complex multi line logic.

2, Why?

It can be seen from the above that a program can realize its required functions without using lambda function. So what do we use it for? We can first roughly analyze the function:

  • Reduce code repeatability
  • Modular code

First, if the same code is used in different parts of the program, we can refine this part of the code into a function and give it a name, so that we can simply realize the functions defined in the function through the name of the function in different places

Second, if the implementation of a function requires a large amount of non repetitive code, the readability of the program will be abnormally low if these codes are written together. At this time, we can divide this large amount of code into multiple functions to realize them respectively and then assemble them.

But if we need a function, it is very short and can be completed in one line; At the same time, it is only called once in the program. So at this time, let's use def to define a function?

In this case, our lambda expression will highlight its advantages! Like the appeal_ The sum function is an example

3, Functional programming in python

Functional programming: it means that every piece of code is immutable and is composed of pure functions. This pure function means that the function itself is independent and does not affect each other. For the same input, there will always be the same output without any side effects.

# Influential function
l = [1,3,5,7]
def my_list(l):
    for index in range(0,len(l)):
        l[index] += 2
    return l
print(f"First call:{my_list(l)}")
print(f"Second call:{my_list(l)}")
# First call: [3, 5, 7, 9]
# Second call: [5, 7, 9, 11]

# No effect
l = [1,3,5,7]
def my_list(l):
    my_arr = []
    for index in range(0,len(l)):
    return l
print(f"First call:{my_list(l)}")
print(f"Second call:{my_list(l)}")
# First call: [1, 3, 5, 7]
# Second call: [1, 3, 5, 7]

# The first is not a pure function, because the value of the array will be changed in each call, so the result will be different each time, while the second has no effect

The advantages of functional programming: its pure function and immutable characteristics make the program more robust and easy to debug and test; The disadvantage is that it is too restrictive and difficult to write, such as scala, but python is not a functional language, but it still provides some functional programming features, such as map(), filter() and reduce(), which are usually used with lambda.
-map(func,iterable) function, which means to call func function for each element in iterable, and finally return a new traversable set

l = [1,2,3,4,5]
new_list = map(lambda x:x+1,l)
print(list(new_list)) #Python 3 is used here, so you need to call list
# [2, 3, 4, 5, 6]

4, Some performance tests:

python3 -mtimeit -s'xs=range(500000)' 'map(lambda x: x+1, xs)'
# 1000000 loops, best of 3: 0.21 usec per loop

python3 -mtimeit -s'xs=range(500000)' '[x+1 for x in xs]'
# 10 loops, best of 3: 41.2 msec per loop

python3 -mtimeit -s'xs=range(500000)' 'l = []' 'for i in xs: l.append(i+1)'
# 10 loops, best of 3: 59.9 msec per loop

# It can be seen that map is the fastest, because the map() function is written directly in C language and does not need to be called indirectly through the Python interpreter at runtime
  • filter(func,iterable) function, which is similar to those parameters and map, and it means that for each element in iterable, func is used to judge and return True or False. Finally, the elements that return True form a new ergodic set
l = [1,2,3,4,5]
new_list = filter(lambda x:x+1,l)
  • reduce(func,iterable) function, which is usually used to do some accumulation operations on a set. Func is also a function object. It is specified that it has two parameters, which represent each element in iterable and the result after the last call. Use func to calculate and return a separate value until the end
from functools import reduce
l = [1,2,3,4,5]
list_sum = reduce(lambda x,y:x+y,l)
# 15

5, Summary

You will find that the functional programming of appeal can be implemented with for loop or list synthesis. How to choose to use it? After the above analysis, it can also be concluded that if our operation on set elements is relatively simple and the amount of data is large, we can give priority to lambda function. If our amount of data is small and the operation of elements is complex, we can give priority to the implementation of for loop or list synthesis

Keywords: Python Back-end

Added by wheelbarrow on Fri, 25 Feb 2022 15:15:13 +0200