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
發佈了36 篇原創文章 · 獲贊 8 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章