Python3入门(五)——函数式编程

一、高阶函数

  1.可以通过变量指向函数,达到类似别名的效果:

>>> f = abs
>>> f(-10)
10

  2.函数的参数可以是函数,也就是函数可以作为一个入参

def add(x, y, f):
    return f(x) + f(y)

  以下介绍几个高阶函数

  map、reduce

    这两个函数就不赘述了。和scala的功能类似,不过用法不一样,它接收两个参数,第一个是函数f,第二个是Iterable。并将计算结果作为新的Iterator返回,惰性的Iterator通过list便可以计算出结果了:

def f(x):
    return x + 1


r = map(f, [1, 2, 3, 4, 5])
print(list(r))

    reduce入参类似map,但是它的f是接收两个参数,并且需要导包。并将结果作为下一次的输入,表示起来就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
from functools import reduce


def f(x, y):
    return x + y


r = reduce(f, [1, 2, 3, 4, 5])
# 注意这里不需要list包装了,因为返回的不是Iterator
print(r)

    filter

  和scala的filter也是类似了,返回Ture的留下,其它过滤掉。其他的入参和返回值与map相同

def f(x):
    return x % 2 == 0


r = filter(f, [1, 2, 3, 4, 5])
print(list(r))

猜你喜欢

转载自www.cnblogs.com/jiangbei/p/8921898.html