How to use the functions of map, filter and reduce in Python
This article mainly introduces how to use the functions of map, filter and reduce in Python. It is very detailed and has certain reference value. If you are interested, you must finish it.
1. Map function
The specification for the map function is to map several functions to all elements of the output list.
Map (function_to_apply, list_of_inputs)
Most of the time, we pass all the elements in the list to each function and collect the output. For example:
Items = [1,2,3,4,5]
Squared = []
For i in items:
Squared.append (iTunes 2)
The Map function allows us to implement it in a simpler, much more beautiful way, as follows:
Items = [1,2,3,4,5]
Squared = list (map (lambda x: Xerox, items))
Most of the time, we use the anonymous function lambdas to cooperate with the map function, not only for the input of the list, but also for the functions of the list!
Def multiply (x):
Return (xonomx)
Def add (x):
Return (xonomx)
Funcs = [multiply, add]
For i in range (5):
Value = map (lambda x: X (I), funcs)
Print (list (value))
# Output:
# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]
2. Filter function
The Filter function is easy to understand, that is, filter filters the elements in the list and returns a list of all elements that meet the requirements, that is, the return value is True when the function is mapped to that element. Here is a simple example to help you understand:
Number_list = range (- 5,5)
Less_than_zero = filter (lambda x: X < 0, number_list)
Print (list (less_than_zero))
# Output: [- 5,-4,-3,-2,-1]
This filter is similar to a for loop, but it is a built-in function and faster.
3. Reduce function
Reduce is a "common" function when you need to perform some calculations on a list and return the results. For example, when you need to calculate the product of a list of integers. Usually in Python you might use the basic for loop to accomplish this task. Now let's try reduce:
From functools import reduce
Product = reduce ((lambda x, y: X * y), [1,2,3,4])
# Output: 24
These are all the contents of the article "how to use the functions of map, filter and reduce in Python". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!