Map, Filter, Reduce的学习笔记
把函数作为参数传入,这样的函数称为高阶函数Higher-order Functions,函数式编程Functional Programming就是指这种高度抽象的编程范式。
Map, Filter, and Reduce are paradigms of functional programming. They allow the programmer (you) to write simpler, shorter code, without neccessarily needing to bother about intricacies like loops and branching.
Essentially, these three functions allow you to apply a function across a number of iterables, in one fell swoop. map
and filter
come built-in with Python (in the __builtins__
module) and require no importing. reduce
, however, needs to be imported as it resides in the functools
module. Let’s get a better understanding of how they all work, starting with map
.
Map
The map()
function in python has the following syntax:
map(func, *iterables)
func
is the function on which each element initerables
(as many as they are) would be applied on.- The asterisk(
*
) oniterables
means there can be as many iterables as possible. - Note that: In Python 2, the
map()
function returns a list. In Python 3, however, the function returns amap object
which is a generator object. To get the result as a list, the built-inlist()
function can be called on the map object. i.e.list(map(func, *iterables))
my_pets = ['alfred', 'tabitha', 'william', 'arla']
uppered_pets = list(map(str.upper, my_pets))
print(uppered_pets) # the output is ['ALFRED', 'TABITHA', 'WILLIAM', 'ARLA']
- The number of arguments to
func
must be the number ofiterables
listed.
circle_areas = [3.56773, 5.57668, 4.00914, 56.24241, 9.01344, 32.00013]
result = list(map(round, circle_areas, range(1,7)))
print(result) # the output is [3.6, 5.58, 4.009, 56.2424, 9.01344, 32.00013]
- Python simply stops when it can’t find the next element in one of the iterables.
circle_areas = [3.56773, 5.57668, 4.00914, 56.24241, 9.01344, 32.00013]
result = list(map(round, circle_areas, range(1,3)))
print(result) # the output is [3.6, 5.58]
Filter
filter()
requires the function to return boolean values (true or false) and then passes each element in the iterable through the function, “filtering” away those that are false. It has the following syntax:
filter(func, iterable)
The following points are to be noted regarding filter()
:
-
Only one iterable is required.
-
The
func
argument is required to return a boolean type. If it doesn’t,filter
simply returns theiterable
passed to it. Also, as only one iterable is required, it’s implicit thatfunc
must only take one argument. -
filter
passes each element in the iterable throughfunc
and returns only the ones that evaluate to true.
scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65]
def is_A_student(score):
return score > 75
over_75 = list(filter(is_A_student, scores))
print(over_75) # the output is [90, 76, 88, 81]
# 保留回文串
dromes = ("demigod", "rewire", "madam", "freer", "anutforajaroftuna", "kiosk")
palindromes = list(filter(lambda word: word == word[::-1], dromes))
print(palindromes) # the output is ['madam', 'anutforajaroftuna']
Reduce
reduce
applies a function of two arguments cumulatively to the elements of an iterable, optionally starting with an initial argument. It has the following syntax:
reduce(func, iterable[, initial])
func
is the function on which each element in theiterable
gets cumulatively applied toinitial
is the optional value that gets placed before the elements of the iterable in the calculation, and serves as a default when the iterable is empty.func
requires two arguments,- the first of which is the first element in
iterable
(ifinitial
is not supplied) - and the second element in
iterable
. - If
initial
is supplied, then it becomes the first argument tofunc
and the first element initerable
becomes the second element.
- the first of which is the first element in
reduce
“reduces” (I know, forgive me)iterable
into a single value.
# sum
from functools import reduce
numbers = [3, 4, 6, 9, 34, 12]
def custom_sum(first, second):
return first + second
result = reduce(custom_sum, numbers)
print(result) # the output is 68
from functools import reduce
numbers = [3, 4, 6, 9, 34, 12]
def custom_sum(first, second):
return first + second
result = reduce(custom_sum, numbers, 10)
print(result) # the output is 78