hopeless-dream

导航

Python的高阶函数

定义

一个函数可以作为另一个函数的变量、参数、返回值等。在数学中,形如y=fn(fn1(x))

两种高阶函数

参数为函数

def foo():
print("foo")


def bar(func):
func()
print("bar")

bar(foo)

返回值为函数

def outer(x):
    def inner(incr=1):
        nonlocal x
        x += 1
        return x

    return inner


foo = outer(5)

注意:上面的函数中,outer和inner对象都在堆上(都是内存地址),调用的时候才会压栈,所以有如下情况:

def outer(x):
    def inner(incr=1):
        nonlocal x
        x += 1
        return x

    return inner


foo = outer(5)
foo1 = outer(5)
print(foo == foo1)

运行结果

False

Python内置的高阶函数filter、map、reduce

filter函数

其功能为:按照函数的的要求过滤可迭代对象iterable中符合条件的元素,返回一个迭代器

接收两个参:

  •   第一个参数为函数fn,fn可以接受一个参数,返回bool
  •   第二个参数为可迭代对象iterable

语法

flter(function,iterable)

举例

k = filter(lambda x: x % 2 == 0, [1, 2, 10])
for i in k:
    print(i)

运行结果

2
10

自己实现

lst = [1, 2, 10]

def filter1(func, iterable):
    ret = []
    for i in iterable:
        if not func(i):
            ret.append(i)
    return ret


print(filter1(lambda x: x % 2, lst))

运行结果

[2, 10]

map函数

接收两个参数,第一个参数为函数fn,第二个参数为多个可迭代对象iterable,返回一个迭代器

语法

map(function,*iterables) -> map object

举例

print(list(map(lambda x:x+1,range(5))))

运行结果

[1, 2, 3, 4, 5]

list结构的map

def _map(fun, iterable):
    ret = []
    for i in iterable:
        ret.append(fun(i))
    return ret


print(_map(lambda x: x + 1, range(5)))

运行结果

[1, 2, 3, 4, 5]

dict结构的map

def _map(fun, iterable):
    ret = {}
    for i in iterable:
        ret.setdefault(fun(i), i)
    return ret


print(_map(lambda x: x + 1, range(5)))        
print(dict(map(lambda x: (x + 1, x), range(5))))         ## 注意,这里的可迭代对象必须是一个二元的

运行结果

{1: 0, 2: 1, 3: 2, 4: 3, 5: 4}
{1: 0, 2: 1, 3: 2, 4: 3, 5: 4}

 reduce函数

接收一个参数为函数,一个为可迭代对象的高阶函数,其返回值为一个值而不是迭代器对象,故其常用与叠加、叠乘等

reduce函数不是内置函数,而是functools模块下提供一下的函数,需要导入

from functools import reduce

lst = [1, 2, 10]
def _reduce(fun, iterable, ini=None):
    if ini is None:
        ret = iterable.pop(0)
    else:
        ret = ini
    for i in iterable:
        ret = fun(ret, i)

    return ret


print(_reduce(lambda x, y: x * y, lst, 100))
print(reduce(lambda x, y: x * y, lst, 100))

运行结果

2000
2000

 

posted on 2020-11-09 23:35  hopeless-dream  阅读(88)  评论(0编辑  收藏  举报