Python中的map、zip、filter、reduce函數使用

來源:互聯網
上載者:User
# -*- coding: utf-8 -*-#1.函數說明:reduce()函數接收的參數和 map()類似,一個函數 f,一個list,但行為和 map()不同,reduce()傳入的函數 f 必須接收兩個參數,reduce()對list的每個元素反覆調用函數f,並返回最終結果值。print("\n###### reduce函數 #####\n")from functools import reducedef f(x, y): return x + yprint (reduce(f,[1, 3, 5, 7, 9], 100))#2.函數說明:map()是 Python 內建的高階函數,它接收一個函數 f 和一個 list,並通過把函數 f 依次作用在 list 的每個元素上,得到一個新的 list 並返回。print("\n###### map函數 #####\n")def ff(x): return x*xprint (list(map(ff,[1, 2, 3, 4, 5, 6, 7, 8, 9])))#lambda實現函數print (list(map(lambda x : x*3 ,[1,2,3,4,[5,6,7]])))#3.函數說明:zip(seq1[,seq2 [...]])->[(seq1(0),seq2(0)...,(...)]。 同時迴圈兩個一樣長的函數,返回一個包含每個參數元組對應元素的元組。若不一致,採取截取方式,使得返回的結果元組的長度為各參數元組長度最小值。print("\n###### zip函數 #####\n")for x,y in zip([1, 2, 3], [4, 5, 6]): print (x,y)#截取到[2,5]for x,y in zip([1, 2, 3], [4, 5]): print (x,y)#4.函數說明:filter(bool_func,seq):此函數的功能相當於過濾器。 調用一個布爾函數bool_func來迭代遍曆每個seq中的元素,返回一個使bool_seq傳回值為true的元素的序列。print("\n###### filter函數 #####\n")print(list(filter(lambda x:x%2 == 0,[1,2,3,4,5])))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.