內置方法map、reduce、filter
阿新 • • 發佈:2017-05-12
enc -- cti initial 代碼實現 cto top 過濾 port
map:
map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from each of the iterables.Stops when the shortest iterable is exhausted.
l1 = [1,2,3,4,5,6,7,8,9] def func(a): return a*10 l2 = map(func,l1) print(l2) # <map object at 0x0000000000A7CB00> 也是一個叠代器 for i in l2: print(i)
reduce:
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
from functools import reduce #內置函數reduce需要導入後才能使用。 l1 = [1,2,3,4,5,6,7,8,9] def func(a,b): return a+b l2 = reduce(func,l1) print(l2)
filter:
filter(function or None, iterable) --> filter object
‘‘‘
Return an iterator yielding those items of iterable for which function(item) is true.
If function is None, return the items that are true.‘‘‘
# 一行代碼實現對列表a中的偶數位置的元素進行加3後求和 a = [1,2,3,4,5] l = sum([j+3 for j in list(filter(lambda i:a.index(i)%2 == 0, a))]) #用到了過濾器和匿名函數 print(l)
內置方法map、reduce、filter