Python uses filter and map functions to process data
In Python,filter and map are two very useful built-in functions that help us process data in a functional programming style.filter function is used to filter elements in a sequence, while map function is used to apply a function to each element in a sequence.
Suppose we have a list of numbers and want to filter out all even numbers and multiply those even numbers by 2. We can use filter and map function to achieve this goal.
Example
Define a list containing numbers
numbers
=
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
]
Use the filter function to filter out even numbers
even_numbers
=
filter
(
lambda
x: x %
2
==
0
,
numbers
)
Use the map function to multiply the even numbers by 2
doubled_even_numbers
=
map
(
lambda
x: x *
2
,
even_numbers
)
Convert the result to a list and print it
result
=
list
(
doubled_even_numbers
)
(
result
)
Code analysis:
numbersis a list containing numbers 1 to 10.filter(lambda x: x % 2 == 0, numbers)Usefilterfunction filters outnumbersthe even numbers in the list.lambda x: x % 2 == 0is an anonymous function used to determine whether a number is even.map(lambda x: x * 2, even_numbers)Usemapfunction to installeven_numbersmultiplies each even number by 2.lambda x: x * 2is an anonymous function used to multiply the input number by 2.list(doubled_even_numbers)data to the child component viamapConvert the result of the function to a list.print(result)Print the final result.
Output result:
Example
[
4
,
8
,
12
,
16
,
20
]
Python3 Examples