Python函数式编程之map/reduce/filter进阶

Python函数式编程之map/reduce/filter进阶

说明

本文重点在于示例代码,在熟悉基本概念(map/reduce/filter/lambda)的基础上阅读最好

背景

函数式编程是一种编程范式,我们常见的是命令式编程,首先大概了解下概念:

命令式:冯诺依曼机的序列

函数式:基于λ演算

函数式编程一般有如下特点:

  • Referential transparency
  • No Side Effect
  • Currying
  • Closure
  • Higher-order function
  • Lazy evaluation
  • Lambda

进入正题,主要看看python函数式编程,几个高阶函数map/reduce/filter的使用

定义(python2)

sequence是一种泛型,包括list,tuple,string

map(function, sequence[, sequence, …]) -> list
1. map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回

reduce(function, sequence[, initial]) -> value
1. 把一个函数作用在一个序列上,reduce把结果继续和序列的下一个元素做累积计算
2. function接受两个参数
3. 返回值类型取决于function return

filter(function or None, sequence) -> list, tuple, or string
1. 如果是None,返回是True的元素
2. 返回和sequence相同的类型

示例

map/reduce/filter其实很简单,要熟练掌握,最好的办法就是code,示例代码包括map/reduce/filter使用的各个方面,重点地方已注释,认真看完code,一定可以掌握map/reduce/filter的

# coding:utf-8
from operator import add


def foo():
    a = [i for i in range(1, 10)]
    b = map(lambda x: x**2, a)
    c = reduce(lambda x, y: x + y, a)
    d = filter(lambda x: not x % 3, a)
    print b
    print c
    print d
'''
[1, 4, 9, 16, 25, 36, 49, 64, 81]
45
[3, 6, 9]
'''


def foo1():
    a = [i for i in range(1, 10)]
    b = map(lambda x: x**2, a)
    b = reduce(lambda x, y, z='hi': z, a)
    # z始终是hi
    b1 = reduce(lambda x, y='hi': y, a)
    # y始终是a中的元素,结束时是最后一个元素
    c = map(lambda x, y='hi': y, a)
    c1 = map(lambda x, y: x - y, a, a)
    d = filter(lambda x, y='hi': y, a)
    # y始终是hi,为True,所以a中没有元素被过滤掉
    print b
    print b1
    print c
    print c1
    print d
'''
hi
9
['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi']
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
'''


def foo2():
    # sequence:list tuple str
    s = "h x010y i"
    # s中每个字符作为参数单独调用
    b = map(lambda x: x, s)
    c = reduce(lambda x, y: x, s)
    # x始终是s的第一个字符(h)
    d = reduce(lambda x, y: y, s)
    e = reduce(lambda x, y: (x,y), s)
    # reduce调用的过程
    f = filter(lambda x: x.isalpha() or x.isspace(), s)
    # 保留字母和空格
    print b
    print c
    print d
    print e
    print f
'''
['h', ' ', 'x', '0', '1', '0', 'y', ' ', 'i']
h
i
(((((((('h', ' '), 'x'), '0'), '1'), '0'), 'y'), ' '), 'i')
h xy i
'''


def foo3():
    a = "a01bcdfalsetrueFalseTrue0None1"
    b = [0, None, False,True, 1, '', 'a']
    c = (0, None, False,True, 1, '', 'a')
    # filter可以接受None作为第一个参数,此时由sequence中
    # 元素本身的真假值进行过滤,返回值保持sequence本身的类型
    print filter(None, a)
    # a中每个字符都是真(0是字符,也为真),返回值是str
    print filter(None, b)
    # 返回值是list
    print filter(None, c)
    # 返回值是tuple
'''
a01bcdfalsetrueFalseTrue0None1
[True, 1, 'a']
(True, 1, 'a')
'''


def foo4():
    bar = [[1, 2, 4, 5], [3, 5, 7, 2, 6]]
    bar1 = ['1', '2', '3']
    b = reduce(add, bar)
    c = map(sum, zip(*bar))
    # 二维数组反转求和
    d = map(int, bar1)
    # 字符串转int
    e = sorted(set(b), key = b.index)
    # 对list去重后,保持原有的元素顺序
    print b
    print c
    print d
    print e
'''
[1, 2, 4, 5, 3, 5, 7, 2, 6]
[4, 7, 11, 7]
[1, 2, 3]
[1, 2, 4, 5, 3, 7, 6]
'''


def foo5():
    a = [i for i in range(1, 4)]
    b = [lambda y: y*x for x in a] # late binding (x延迟绑定)
    c = [lambda y, x=x: y*x for x in a] # x是local变量
    d = (lambda y: y*x for x in a) # lazy evaluation(生成器惰性求值)
    e = map(lambda x: lambda y: y*x, a) # closure(闭包)
    for bar in b:
        print bar(2)
    print '--------'
    for bar in c:
        print bar(2)
    print '--------'
    for bar in d:
        print bar(2)
    print '--------'
    for bar in e:
        print bar(2)
    print '--------'

    for t in e:
        for j in t.__closure__:
            print j.cell_contents

'''
6
6
6
--------
2
4
6
--------
2
4
6
--------
2
4
6
--------
1
2
3
'''

if __name__ == '__main__':
    foo()
    foo1()
    foo2()
    foo3()
    foo4()
    foo5()
    pass

你可能感兴趣的:(Python)