zoukankan      html  css  js  c++  java
  • Learning Python 012 函数式编程 1 高阶函数

    Python 函数式编程 1 高阶函数

    高阶函数

    Q:什么是高阶函数
    A:一个函数接收另一个函数作为参数这种函数就称之为高阶函数
    简单举个例子:

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

    使用这个函数:

    >>> add(-5, 6, abs)
    11

    它是这样执行的:

    x = -5
    y = 6
    f = abs
    f(x) + f(y) ==> abs(-5) + abs(6) ==> 11
    return 11

    map/reduce

    map

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

    def f(x):
        return x * x
    r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    
    print(r)
    print(list(r))

    运行:

    <map object at 0x000000821D2A11D0>
    [1, 4, 9, 16, 25, 36, 49, 64, 81]

    由于结果r是一个IteratorIterator惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list

    再比如,把这个list所有数字转为字符串

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

    reduce

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

    举个例子:一个序列求和

    >>> from functools import reduce
    >>> def add(x, y):
    ...     return x + y
    ...
    >>> reduce(add, [1, 3, 5, 7, 9])
    25

    当然求和运算可以直接用Python内建函数sum(),没必要动用reduce

    >>> sum([1, 3, 5, 7, 9])
    25

    再举个例子:把序列[1, 3, 5, 7, 9]变换成整数13579

    >>> 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):
    ...     return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
    ...
    >>> reduce(fn, map(char2num, '13579'))
    13579

    整理代码:

    from functools import reduce
    
    def str2int(s):
        def fn(x, y):
            return x * 10 + y
        def char2num(s):
            return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
        return reduce(fn, map(char2num, s))

    总结:
    假设Python没有提供int()函数,你完全可以自己写一个把字符串转化为整数的函数,而且只需要几行代码!

    filter

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

    举例:

    一个list中,删掉偶数,只保留奇数:

    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']

    strip()函数用法:
    当没有形参传入strip()函数时,默认删除空白符(包括' ', ' ', ' ‘, ' '
    strip()函数的具体用法请到这里学习:http://www.cnblogs.com/kaituorensheng/archive/2013/05/23/3096028.html


    filter()函数返回的是一个Iterator,所以 要强迫filter()完成所有计算,就使用list()函数获取所有结构,返回一个list.

    sorted

    sorted()函数是:排序算法。

    >>> 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'])
    ['Credit', 'Zoo', 'about', 'bob']

    默认的排序规则是:按照ASCII的大小比较的,由于'Z' < 'a',所以,大写字母Z会排在小写字母a的前面。

    sorted传入key函数,忽略大小写的排序:

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

    实现反向排序,传入第三个参数reverse=True

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

    参考网站:
    http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014318230588782cac105d0d8a40c6b450a232748dc854000

  • 相关阅读:
    SuperMap房产测绘成果管理平台
    SuperMap产权登记管理平台
    Android adb shell am 的用法(1)
    由浅入深谈Perl中的排序
    Android 内存监测和分析工具
    Android 网络通信
    adb server is out of date. killing...
    引导页使用ViewPager遇到OutofMemoryError的解决方案
    adb logcat 详解
    How to send mail by java mail in Android uiautomator testing?
  • 原文地址:https://www.cnblogs.com/aobosir/p/5928634.html
Copyright © 2011-2022 走看看