python內建函數filter(),map(),reduce()筆記

來源:互聯網
上載者:User

標籤:集合   lam   列操作   lis   函數返回   元組   red   傳遞   python re   

‘‘‘
python reduce()函數:
reduce()函數會對參數序列中元素進行積累。

函數將一個資料集合(鏈表,元組等)中的所有資料進行下列操作:用傳給reduce中的函數 function(有兩個參數)
先對集合中的第 1、2 個元素進行操作,得到的結果再與第三個資料用 function 函數運算,最後得到一個結果。

文法:ruduce()
reduce(function,iterable,initializer)
參數:function-函數,有兩個參數
iterable--可迭代對象
initializer--可選,初始參數
傳回值:返回Function Compute結果:
‘‘‘
def add(x,y):
return x+y
print reduce(add,[1,2,3,4,5])
>>>15
#相當於
print reduce(lambda x,y:x+y,[1,2,3,4,5])
>>> 15
‘‘‘
python的map函數
map()會根據提供的函數對指定序列做映射
第一個參數function以參數序列匯總的每一個元素中調用function函數,返回包含每次 function 函數傳回值的新列表。
文法:
map()函數文法:
map(function,iterable,...)
參數

function -- 函數,有兩個參數
iterable -- 一個或多個序列

傳回值

返回列表。
‘‘‘
def map_fun(x):
return x**2
print map(map_fun,[1,2,3,4,5])
>>> [1,4,9,16,25]
print map(lambda x:x**2,[1,2,3,4,5])
>>> [1,4,9,16,25]

‘‘‘
Python filter() 函數
描述:
filter() 函數用於過濾序列,過濾掉不合格元素,返回由符合條件元素組成的新列表。

該接收兩個參數,第一個為函數,第二個為序列,序列的每個元素作為參數傳遞給函數進行判段,然後返回 True 或 False,最後將返回 True 的元素放到新列表中。
‘‘‘
print filter(lambda x:x%2==0,[1,2,3,4,5])

import math
print filter(lambda x:math.sqrt(x)%1==0,range(1,101))
>>> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


import math
def is_sqr(x):
return math.sqrt(x) % 1==0
newlist = filter(is_sqr,range(1,101))
print newlist
>>> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


python內建函數filter(),map(),reduce()筆記

聯繫我們

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