美文网首页
Python 高阶函数

Python 高阶函数

作者: _YZG_ | 来源:发表于2017-12-11 16:31 被阅读51次

编写高阶函数,就是让函数的参数能够接收别的函数

变量可以指向函数

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

函数名也是变量

>>> abs = 10
>>> abs(-10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

传入函数

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

print(add(-5, 6, abs))

11

map/reduce

map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

>>> def f(x):
...     return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]


>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']


reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数
reduce把结果继续和序列的下一个元素做累积计算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)


>>> from functools import reduce
>>> def fn(x, y):
...     return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579

str 转换成int
>>> from functools import reduce
>>> def fn(x, y):
...     return x * 10 + y
...
>>> def char2num(s):
...     digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
...     return digits[s]
...
>>> reduce(fn, map(char2num, '13579'))
13579


整理成一个str2int的函数就是:

from functools import reduce

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def str2int(s):
    def fn(x, y):
        return x * 10 + y
    def char2num(s):
        return DIGITS[s]
    return reduce(fn, map(char2num, s))


还可以用lambda函数进一步简化成:

from functools import reduce

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def char2num(s):
    return DIGITS[s]

def str2int(s):
    return reduce(lambda x, y: x * 10 + y, map(char2num, s))

filter

和map()类似,filter()也接收一个函数和一个序列。
和map()不同的是,filter()把传入的函数依次作用于每个元素,
然后根据返回值是True还是False决定保留还是丢弃该元素。


def is_odd(n):
    return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]


把一个序列中的空字符串删掉,可以这么写:
def not_empty(s):
    return s and s.strip()

list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))
# 结果: ['A', 'B', 'C']

注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list。

filter()的作用是从一个序列中筛出符合条件的元素。
由于filter()使用了惰性计算,所以只有在取filter()结果的时候,才会真正筛选并每次返回下一个筛出的元素。

sorted

sorted()也是一个高阶函数。用sorted()排序的关键在于实现一个映射函数。

Python内置的sorted()函数就可以对list进行排序:
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]

此外,sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']

反向排序
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']

相关文章

  • python装饰器

    装饰器简述 要理解装饰器需要知道Python高阶函数和python闭包,Python高阶函数可以接受函数作为参数,...

  • Python高阶函数

    本文要点 1.什么是高阶函数 2.python中有哪些常用的高阶函数 什么是高阶函数? 在了解什么是高阶函数之前,...

  • wangyanhua--python2

    基本函数的使用 匿名函数 常用系统高阶函数 高阶函数 常用系统高阶函数 Python递归 安装第三方库 三国小说人...

  • Python函数式介绍一 - 高阶函数

    Python函数式介绍一 - 高阶函数Python函数式介绍二 - 链式调用 最近为了给朋友推广Python函数式...

  • Python高阶函数学习笔记

    python中的高阶函数是指能够接收函数作为参数的函数 python中map()函数map()是 Python 内...

  • 【Python】-014-函数-函数式编程-2

    python内置高阶函数 Filter函数filter(function, sequence) -> list, ...

  • 函数式编程--高阶函数

    高阶函数英文叫Higher-order function。什么是高阶函数?举例说明。变量可以指向函数以Python...

  • 高阶函数(Python)

    什么是高阶函数(Python)? 高阶函数:能接收函数做参数的函数 变量可以指向函数 函数的参数可以接受变量 一个...

  • filter函数有点意思

    filter函数 filter(function, iterable)filter函数是python中的高阶函数,...

  • 高阶python 函数式编程

    高阶python 函数式编程 - 函数式 函数式编程(FunctionalProgramming) - 基于lam...

网友评论

      本文标题:Python 高阶函数

      本文链接:https://www.haomeiwen.com/subject/attiixtx.html