Filter: Implementing map reduce with lambda functions (python)
The filter
function is useful to reduce the amount of elements that there is in a list. It
is quite performatic and composes part of map reduce techniques provided by python.
The filter function
basically receives two parameters. The first one is the function that will
verify if a certain element keeps in the produce list or not, basically it has
to compare a certain element with a criteria and if it returns true the element
is preserved, otherwise not. The second parameter is the list to be filtered.
The output of the filter function is another list with filtered elements.
Important! The filter does not change the original list, but produces a new
one.
print("### FILTER ###")
number_list = range(-5, 5)
print("original list:")
print(number_list)
# Using normal function
def biggerThanZero(x):
return
x > 0
bigger_than_zero = list(filter(biggerThanZero, number_list)) # filter(function,
list)
print("filtered list (bigger than zero):")
print(bigger_than_zero
)
The first parameter
could be any function, or defined with “def” keyword as presented in the example
above, or even defined as a lambda function, as presented below. The
performance of functions will be de same. The usage of lambda function is just
a way to implement the a function with a different code structure, more related
to functional programming techniques.
# Using lambda function
less_than_zero = list(filter(lambda x: x < 0, number_list)) # filter(function, list)
print("filtered list (small then zero):")
print(less_than_zero)
The complete
code is available to be downloaded here:
https://github.com/rafaelqg/code/blob/main/filter_lambda.py
You may see
a video class about this video here:
https://www.youtube.com/watch?v=B64R0_jWsns
Comments
Post a Comment