Talking about Python functional programming

Anonymous function lambda expression

**What is an anonymous function? **

An anonymous function, as the name implies, is a function without a name. You don't need to use def to define in the program, you can directly use the lambda keyword to write simple code logic. Lambda is essentially a function object, which can be assigned to another variable, and then the function can be called by the variable, or it can be used directly.

# Usually, we define the function first, and then call it
def power(x):return x **2print(power(2))

# When using lambda expressions, we can operate like this
power = lambda x : x **2print(power(2))

# Feel too troublesome, you can also call like this
print((lambda x:2* x)(8))

The basic format of lambda expression: lambda input parameter: expression

# There can be multiple input parameters, such as
power = lambda x, n: x ** n

print(power(2,3))

Usage scenarios of lambda expressions

Generally suitable for creating some temporary, small functions. For example, the power function above, we can of course use def to define, but using lambda to create it will be very concise, especially in the use of higher-order functions.

Define a function, pass in a list, and add 1 to the value of each element of the list

def add(l =[]):return[x +1for x in l]print(add([1,2,3]))

The above function is changed to add 2 to the value of all elements

You may say that this is not easy, just change the 1 in return to 2. But does it really work? What if the function is used in multiple places, but the other places do not want to add 2?

This is easy to handle, extract the part that becomes, let the caller pass

def add(func,l =[]):return[func(x)for x in l]

def add1(x):return x+1

def add2(x):return x+2print(add(add1,[1,2,3]))print(add(add2,[1,2,3]))

A simple question must be realized with so much code?

def add(func,l =[]):return[func(x)for x in l]print(add(lambda x:x+1,[1,2,3]))print(add(lambda x:x+2,[1,2,3]))

map function

Basic format of map

map(func, *iterables)

The map() function receives more than two parameters. The first one is a function, and the rest is a sequence. The passed function is applied to each element of the sequence in turn, and the result is returned as a new sequence. Which is similar to map(func,[1,2,3])

Similarly, we still come to complete such a function: add 1 to the value of each element of the list

def add(x):return x +1

result =map(add,[1,2,3,4])print(type(result))print(list(result))

Use lambda expressions to simplify operations

result =map(lambda x: x +1,[1,2,3,4])print(type(result))print(list(result))

The format of the map function with two parameters in the function

Use the map function to sum the corresponding positions of the data in the two sequences, and then return, that is, after operating on the two sequences [1,2,3],[4,5,6], return the result [5,7, 9]

print(list(map(lambda x, y: x + y,[1,2,3],[4,5,6])))

It is relatively easy to understand if the number of elements in the two sequences is the same. If the two sequences have different numbers, will an error be reported?

print(list(map(lambda x, y: x + y,[1,2,3],[4,5])))

We can see that no error will be reported, but the result is subject to the fewest

reduce function

Basic format of reduce function

reduce(function, sequence, initial=None)

Reduce applies a function to a sequence. This function must receive two parameters. The reduce function continues to calculate the result with the next element of the sequence. It is similar to recursion. The reduce function will be applied to this time by the previous calculation result. Calculating

reduce(func, [1,2,3]) = func(func(1, 2), 3)

Use the reduce function to calculate the product of a list

from functools import reduce

def func(x, y):return x * y

print(reduce(func,[1,2,3,4]))

Combine lambda expressions to simplify operations

from functools import reduce

print(reduce(lambda x, y: x * y,[1,2,3,4]))

filter function

Filter, as the name implies, means to filter, with impurities (unnecessary data), after being processed by the filter, it is filtered out.

The basic format of the filter function

filter(function_or_None, iterable)

filter() receives a function and a sequence. Apply the passed function to each element in turn, and then decide whether to keep or discard the element according to whether the return value is True or False.

Use the filter function to operate on a given sequence, and finally return all even numbers in the sequence

print(list(filter(lambda x: x %2==0,[1,2,3,4,5])))

sorted function

Sorted can be seen literally, this is a function for sorting, sorted can sort all iterable objects

Basic format of sorted

sorted(iterable, key=None, reverse=False)

# iterable --Iterable object.
# key --The main element used for comparison has only one parameter. The parameters of the specific function are taken from the iterable object and specify an element in the iterable object for sorting.
# reverse --Sorting rules, reverse=True descending, reverse=False ascending order (default).

# Sort the sequence in ascending order
print(sorted([1,6,4,5,9]))

# Sort the sequence in descending order
print(sorted([1,6,4,5,9], reverse=True))

# Sort lists that store multiple lists
data =[["Python",99],["c",88]]print(sorted(data, key=lambda item: item[1]))

Closure

In Python where everything is an object, can a function be returned as the return value of a function?

def my_power():
 n =2
 def power(x):return x ** n
 return power

p =my_power()print(p(4))

#------------------------------------------------------------
def my_power():
 n =2
 def power(x):return x ** n
 return power

n =3
p =my_power()print(p(4))

We can see that when the my_power function returns, it also brings back the referenced value (n). The value of n is used by the new function. In this case, we call it a closure.

When we remove the value of n out of the my_power function, let’s look at the calculation result at this time

n =2

def my_power():
 def power(x):return x ** n
 return power

n =3
p =my_power()print(p(4))

Why is the output result 64?

Let's first look at the result of p.closure__ when closing

# example 1
def my_power():
 n =2
 def power(x):return x ** n
 return power

p =my_power()print(p.__closure__)

# result:(<cell at 0x00000264518F9A38: int object at 0x00007FFA7F617120)
# closure is an attribute of the internal function, used to save environment variables

#---------------------------------------------------------------------

# Example 2
n =2
def my_power():
 def power(x):return x ** n
 return power

n =3
p =my_power()print(p.__closure__)

# Output result None

By comparing Example 1 with Example 2, we can know that Example 2 is not a closure

Classical closure problems

Is the following program a closure? Can it run correctly

def my_power():
 n =2
 
 def power(x):
 n +=1return x ** n
 
 return power

p =my_power()print(p(3))

How to make the above program run correctly? Look at the result after correction

def my_power():
 n =2
 
 def power(x):
 nonlocal n
 n +=1return x ** n
 
 return power

p =my_power()print(p.__closure__)print(p(3))print(p(3))

Look at the results of the following program

def my_power():
 n =2
 L =[]for i inrange(1,3):
 def power():return i ** n
  
 L.append(power)return L

f1, f2 =my_power()print(f1())print(f2())print(f1.__closure__[0].cell_contents)print(f2.__closure__[0].cell_contents)

The python function will look for the value of the variable in the function body only when it is executed, that is to say, you are not even sure of the formal parameters, how do you know what i is? Here, you only need to remember that if you are not sure about the formal parameters, python will only remember the last i value.

Decorator and its application

What is decorator mode

The Decorator Pattern allows adding new features to an existing object without changing its structure. This type of design pattern belongs to the structural pattern, which serves as a wrapper for existing classes.

This mode creates a decorative class to wrap the original class and provides additional functions while maintaining the integrity of the class method signature.

import time

start = time.time()
time.sleep(4)
end = time.time()print(end - start)

Look at the decorator from a practical example

def my_fun():print("This is a function")my_fun()

Print "This is a function" before printing one more line of hello world.

def my_fun():
 begin = time.time()
 time.sleep(2)print("Here is a function")
 end = time.time()print(end-begin)my_fun()

At this time, if you don't want to modify the original function, how can you fix it?

def my_fun():print("This is a function")

def my_time(func):
 begin = time.time()
 time.sleep(2)func()
 end = time.time()print(end - begin)my_time(func)

In this way, all business callers have to modify because of the need to add functions. This method is obviously undesirable.

another way:

def print_cost(func):
 def wrapper():
 begin = time.time()
 time.sleep(2)func()
 end = time.time()print(end - begin)return wrapper

@ print_cost
def my_fun():print("Here is a function")

The second method does not modify the internal implementation of the func function, but uses the decorator mode to decorate and enhance its function.

The above is the detailed content of Python functional programming. For more information about Python functional programming, please pay attention to other related articles on ZaLou.Cn!

Recommended Posts

Talking about Python functional programming
Talking about Python coroutine
Talking about inheritance in Python
Talking about strings in Python
Talking about php calling python files
Talking about the modules in Python
Python network programming
Talking about Python multithreading and program lock
12. Network Programming in Python3
Detailed Python IO programming
Python GUI interface programming
Learn about Python3 coroutine
Python programming Pycharm fast learning
Google Python Programming Style Guide
Python3 script programming commonly used.md
Analysis of Python object-oriented programming
XTU programming Python training three
Black Hat Programming Application Python2
Black hat programming application of Python1
Learn about garbage collection in Python
How to understand python object-oriented programming
Python classic programming questions: string replacement