Functional Programming or functional programming is a programming paradigm.
It treats computer operations as mathematical function operations and avoids the use of program state and variable objects.
The above are just simple functional programming concepts, we only need to understand them briefly.
In Python, functional programming mainly consists of the use of several functions: lambda(), map(), reduce(), filter(), etc.
lambda function becomes an anonymous function. A lambda function can only have one expression, and there is no need to write return to return the value of the function. Of course, the anonymous function is also a function object, and the anonymous function can also be assigned to a variable.
You can also return anonymous functions as return values
It can be seen that the variable f is a lambda function type, you need to use f() to call this function.
The map function receives two parameters, one is a function and the other is an Interable (iterable sequence). The map function applies the function to each element of the sequence in turn, and Return the result as a new Interable.
Look at an example:
A simple list analysis, add 2 to each element of list a, using the map function can be written as:
Since the map function returns a lazy sequence, it needs to be called through functions such as list().
Although the above code looks more complicated than writing a for loop directly, when the amount of data is large, the efficiency of Python's for is not very high, while the efficiency of map can be close to that of C language. . At the same time, the code is also much simpler, and it is like an X artifact.
Another small example, convert the elements in the list into strings, a command
It and Map is somewhat similar, but map is used for iteration one by one, while the reduce function is used for recursive calculations.
A simple sequence summation
#Sum each element of list a in sequence, and then look at an example of a homemade int() function
This is the usage of Python's built-in function int
We can also achieve the following through the reduce and map functions
First use the map function to traverse the string list 23465, and then recursively apply each element of the list to the lambda function through the reduce function.
It also receives a function and a sequence. filter() applies the passed function to each element in turn, and then decides to retain it based on whether the return value is True or False. Or discard the element.
Using these functions can not only make our code more concise, but also greatly improve efficiency when the amount of data is large or the calculation is intensive.
The above is the detailed content of Python functional programming everyone should know. For more information, please follow other related articles on the PHP Chinese website!