Python Using `filter` and `map` Functions to Process Data
In Python,filterandmapare two very useful built-in functions that can help us process data in a functional programming way.filterThe function is used to filter elements in the sequence, whilemapthe function is used to apply a function to each element in the sequence.
Suppose we have a list of numbers, we want to filter out all even numbers and multiply these even numbers by 2. We can usefilterandmapfunction 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 even numbers by 2
doubled_even_numbers = map(lambda x: x * 2, even_numbers)
# Convert the result to a list and print
result = list(doubled_even_numbers)
print(result)
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 even numbers by 2
doubled_even_numbers = map(lambda x: x * 2, even_numbers)
# Convert the result to a list and print
result = list(doubled_even_numbers)
print(result)
Code analysis:
numbersis a list containing numbers 1 to 10.filter(lambda x: x % 2 == 0, numbers)Usefilterfunction to filter 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 toeven_numbersmultiply each even number in it by 2.lambda x: x * 2is an anonymous function used to multiply the input number by 2.list(doubled_even_numbers)willmapConvert the result of the function to a list.print(result)Print the final result.
Output:
Example
[4, 8, 12, 16, 20]
Python3 Examples