Python: Map, Filter, Reduce

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 filtercome 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 in iterables (as many as they are) would be applied on.
  • The asterisk(*) on iterables 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 a map object which is a generator object. To get the result as a list, the built-in list() 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 of iterables 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 the iterable passed to it. Also, as only one iterable is required, it’s implicit that func must only take one argument.

  • filter passes each element in the iterable through func 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 the iterable gets cumulatively applied to
  • initial 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 (if initial is not supplied)
    • and the second element in iterable.
    • If initial is supplied, then it becomes the first argument to func and the first element in iterable becomes the second element.
  • 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值