python的reduce,map,zip和filter函數

來源:互聯網
上載者:User

標籤:print   filter   color   def   序列   使用   int   style   add   

一、    reduce(function,Iterable),它的形式和map()函數一樣。不過參數function必須有兩個參數。

reduce()函數作用是:把結果繼續和序列的下一個元素做累積計算。

例,
    
    >>>def add(x, y) :            # 兩數相加
    ...     return x + y
    ...
    >>> reduce(add, [1,2,3,4,5])   # 計算資料行表和:1+2+3+4+5
    15
    >>> reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函數
    15




二、    map(function,Iterable)是將列表中的每一個元素作用於函數。

1.傳回值:

    Python 2.x 返回列表。

    Python 3.x 返回迭代器。
所以python3中擷取map傳回值的兩個基本方法:
    ①print(list(map(f,Iter)))      #這裡的f代表函數,Iter代表可迭代對象。
    ②使用 for 迴圈。


例,
    ①m = map(lambda x : x + 1, [1, 2, 3])
      print(list(m))   #結果為:[5, 7, 9]

    ②提供了兩個列表,對相同位置的列表資料進行相加
      >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
      [3, 7, 11, 15, 19]




三、    zip函數接受任意多個可迭代對象作為參數,將對象中對應的元素打包成一個tuple,然後返回一個可迭代的zip對象。
例,
    lt1 = [‘a‘, ‘b‘, ‘c‘]
    lt2 = [1, 2, 3]
    lt3 = [‘A‘, ‘B‘, ‘C‘]
    result = list(zip(lt1, lt2, lt3))
    print(result)   #輸出結果:[(‘a‘, 1, ‘A‘), (‘b‘, 2, ‘B‘), (‘c‘, 3, ‘C‘)]



四、    filter() 函數用於過濾序列,過濾掉不合格元素,返回由符合條件元素組成的新列表。
    filter接收兩個參數,第一個為函數,第二個為序列,序列的每個元素作為參數傳遞給函數進行判,然後返回 True 或 False,最後將返回 True 的元素放到新列表中。
    文法:filter(function, Iterableble)

例,
    func = lambda x : x % 2 == 1
    print(list(filter(func, [1,2,3]))) #輸出結果:[1, 3]

python的reduce,map,zip和filter函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.