天天看點

python内置函數 filter、map,reduce

filter(func,itrable) 過濾

序列中的每個元素作為參數傳遞給函數進行判斷,傳回True或者False,最後将傳回True的元素放到新清單中

# eg: 奇數的判斷
 def is_odd(n):
     return n%2 == 1
 templist = filter(is_odd,[1,2,3,4,5,6,7,8,9,10])

 newlist = list(templist)
 print(newlist)
           

map(func,itrable)

将傳入的函數依次作用到序列的每個元素,并把結果作為新的list傳回

def f(x):
     return x*x
 templist = map(f,[1,2,3,4,5,6])
 newlist = list(templist)
 print(newlist)
           

reduce(func,itrable[, initial])

函數會對參數序列中的元素進行累積,python3中,放置在functools子產品中

from functools import reduce
 def add(x,y):
     return x+y
 res = reduce(add,[1,2,3,4,5])
 res = reduce(lambda x,y:x+y,[1,2,3,4,5])
 print(res)
           
# ex: 統計sentences = ['The Deep Learning textbook is a resource intended to help students and practitioners enter the field of machine learning in general and deep learning in particular.']中‘learning’出現的次數。
sentences = ['The Deep Learning textbook is a resource intended to help students and practitioners enter the field of machine learning in general and deep learning in particular.']
from functools import reduce
word_count = reduce(lambda a,x:a+x.count("learning"),sentences,0)
print(word_count)