🚀 Author: "big data Zen"
🚀 Fan benefits: Join the big data community of xiaozen
🚀 Welcome to praise 👍, Collection ⭐, Leaving a message. 💬
python functional programming
Advanced knowledge points: introduce the use of anonymous functions lambda, higher-order functions map, reduce, filter and sorted
Usage and usage scenarios of lambda expressions
What is an anonymous function?
Anonymous functions, as the name suggests, are functions without names. They do not need to be defined by def 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**
Normally, we define the function first and then call it:
def power(x): return x ** 2 print(power(2))
When using lambda expressions, we can do this
power = lambda x : x ** 2 #The front x represents an input parameter of the function, and the rear x represents an operation on the input parameter print(power(2)) Output: 4 I think it's too troublesome. You can call it like this print((lambda x: 2 * x)(8)) Output: 16
Basic format of ambda expression
lambda arguments: expressions
There can be multiple input parameters, such as
power = lambda x, n: x ** n print(power(2, 3))
Usage scenario of lambda expression
It is generally suitable for creating some temporary and compact functions. For example, for the above power function, we can certainly use def to define it, but it will be very concise to use lambda to create it, especially in the use of high-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 +1 for x in l] print(add([1,2,3])) Output: [2,3,4]
The above function is changed to add 2 to the values of all elements. You may say that this is not simple. Just change 1 in return to 2. But really? What if the function is used in more than one place, and other places don't want to add 2? It's easy to do. Pull out the change part and let the caller pass it on
def add(func,l = []): return [func(x) for x in l] def add1(x): return x+1 def add2(x): return x+2 print(add(add1,[1,2,3])) print(add(add2,[1,2,3])) Output: [2, 3, 4] [3, 4, 5] A simple question must be implemented 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 of higher-order functions in Python
*Basic format of map(func, iterables)
The map() function receives more than two parameters. The first one is a function and the rest is a sequence. The incoming functions are applied to the sequence in turn
And return the result as a new sequence. That is, similar to map(func,[1,2,3])
Similarly, let's complete the function of adding 1 to the value of each element of the list
def add(x): return x + 1 result = map(add, [1, 2, 3, 4]) #It means that the add operation is performed on the following sequences print(type(result)) print(list(result)) #If the list is not added for conversion, it will output: < map object at 0x000002168c98edc8 > Output: <class 'map'> [2, 3, 4, 5] use lambda Expression simplification operation result = map(lambda x: x + 1, [1, 2, 3, 4]) print(type(result)) print(list(result))
map function format with two parameters in function
Use the map function to sum the two corresponding positions and then return them, that is, after operating the [1,2,3] and [4,5,6] sequences, return the results [5,7,9].
print(list(map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6]))) Output: [5, 7, 9] For two sequence elements with the same number, it is relatively easy to understand. If the number of two sequences is different, will an error be reported? print(list(map(lambda x, y: x + y, [1, 2, 3], [4, 5]))) Output: [5,7] We can see that no error will be reported, but the result shall be subject to the small number
reduce of higher-order functions in Python
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 the cumulative calculation of the result and the next element of the sequence. It is somewhat similar to recursion. The reduce function will be applied to this calculation by the previous calculation result.
reduce(func, [1,2,3]) = func(func(1, 2), 3) #It means that the results of 1 and 2 will be calculated first and applied to the next calculation use 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])) #1*2,2*3,6*4 Output: 24 from functools import reduce def func(x, y): return x * y print(reduce(func, [1, 2, 3, 4],2)) #The latter 2 is the initial value. You don't need to write initial=2. Just write 2 directly. The calculation result is 48. During the calculation process, the initial value 2 will be multiplied by 1, and then the result 2 will be multiplied by 2 and accumulated in turn combination lambda Expressions, simplifying operations from functools import reduce print(reduce(lambda x, y: x * y, [1, 2, 3, 4]))
filter of higher-order function in Python
As the name suggests, filter means filtering. The data with impurities (unnecessary data) will be filtered out after being processed by filter.
Basic format of filter function
filter(function_or_None, iterable)
filter() receives a function and a sequence. The incoming function is applied to each element in turn, and then the return value is**
True or False determines whether the element is retained or discarded.
Use the filter function to operate on the given sequence, and finally return all even numbers in the sequence
print(list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5]))) Output: [2,4]
sorted of higher order functions in Python
orted literally, this is a function for sorting. sorted can sort all iteratable objects
Basic format of sorted:
sorted(iterable, key=None, reverse=False) iterable -- Iteratable objects. key -- The element is mainly used for comparison. There is only one parameter. The parameters of the specific function are taken from the iteratable object, which refers to Sort by specifying an element in an iteratable object. reverse -- Collation, reverse = True In descending order, reverse = False Ascending (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 a list that stores multiple lists
data = [["Python", 99], ["c", 88]] print(sorted(data, key=lambda item: item[1])) #item: item[1]) locate the following number and sort according to the following number. If not specified, sort according to the size of the first number. key=lambd this means that the small list in the large list is passed into our anonymous expression as an item. Item is not a keyword and can be changed #Output: [['c', 88], ['Python', 99]]