Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python using filter and map functions to process data

Python uses filter and map functions to process data

Document Object Reference Manual Python3 Examples

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

)

print

(

result

)

Code analysis:

  1. numbers is a list containing numbers 1 to 10.
  2. filter(lambda x: x % 2 == 0, numbers) Use filter function filters out numbers the even numbers in the list.lambda x: x % 2 == 0 is an anonymous function used to determine whether a number is even.
  3. map(lambda x: x * 2, even_numbers) Use map function to install even_numbers multiplies each even number by 2.lambda x: x * 2 is an anonymous function used to multiply the input number by 2.
  4. list(doubled_even_numbers) data to the child component via map Convert the result of the function to a list.
  5. print(result) Print the final result.

Output result:

Example

[

4

,

8

,

12

,

16

,

20

]

Document Object Reference Manual Python3 Examples