Python的sum、map、filter和reduce

最近在看《Think Python》(英文版),看到了講解map, reduce, filter等函數,以爲講解的思路特別好。因此,我加上了本身的理解,寫了本篇文章。python

引子

若是要對列表中的數字求和,咱們能夠這樣作:api

def add_all(t):
    """t is a list of nums"""
    total = 0
    for x in t:
        total += x

    return total

運行結果:
運行結果函數

因爲python中求和操做太常見了,因此python提供了內置函數sum來進行這項操做spa

sum

將上一版代碼修改以下:code

if __name__ == '__main__':
    t = [1, 2, 3, 4]
    print sum(t)

運行結果:
運行結果blog

像這種從一個列表中得出一個結果的操做,也叫reduce,除了求和這一種reduce操做外,python還支持自定義的方式隊列

reduce

好比,我不是想對隊列求和,而是想獲得列表各數字的乘積,能夠利用reduce這樣實現:ip

def multiple_all(x, y):
    return x * y

if __name__ == '__main__':
    t = [1, 2, 3, 4]
    print reduce(multiple_all, t)

運行結果:
運行結果rem

上面介紹了將一個從一個列表獲得一個結果的情形,還有一種情形是:按照某個規律對列表中的元素一一轉換,這就要用到map內置函數了字符串

map

若是給定一個列表(元素爲字符串),要把列表元素首字母大寫,能夠這樣作

if __name__ == '__main__':
    t = ['hello', 'world', 'yarving']
    print map(lambda x: x.capitalize(), t)

運行結果:
運行結果

還有一種狀況,是要將列表裏的元素過濾出去,能夠用到filter函數

filter

給定一個列表(元素爲數字),若是要僅保留不大於4的數字,能夠這樣作:

if __name__ == '__main__':
    t = [1, 2, 3, 4, 5, 6, 7]
    print filter(lambda x: x <= 4, t)

運行結果:
運行結果

獲取《Think Python》(英文版)電子書

如想要獲取《Think Python》(英文書)的PDF版本,可發送郵件到 yarving@qq.com ,並標明主題 "Think Python"

本文做者: Yarving Liu
本文連接: http://yarving.historytale.co...版權聲明: 本博客全部文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明出處!

相關文章
相關標籤/搜索