map()
map returns an iterator.
map takes a function and applied the function to every item of iterable.
If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.
內(nèi)置函數(shù)map()可以將一個函數(shù)依次映射到序列或迭代器對象的每個元素上,并返回一個可迭代的map對象作為結(jié)果幅疼,map對象中每個元素是原序列中元素經(jīng)過該函數(shù)處理后的結(jié)果,該函數(shù)不對原序列或迭代器對象做任何修改。
list(map(add5, range(10))) #把單參數(shù)函數(shù)映射到一個序列的所有元素
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> a = [1, 2, 3, 4]
>>> b = [1, 2, 3, 4]
>>> result = list(map(lambda x, y: x + y, a, b))
>>> result
[2, 4, 6, 8]
reduce()
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.
標(biāo)準(zhǔn)庫functools中的函數(shù)reduce()可以將一個接收2個參數(shù)的函數(shù)以迭代累積的方式從左到右依次作用到一個序列或迭代器對象的所有元素上,并且允許指定一個初始值。例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])計算過程為((((1+2)+3)+4)+5),第一次計算時x為1而y為2捌臊,再次計算時x的值為(1+2)而y的值為3,再次計算時x的值為((1+2)+3)而y的值為4兜材,以此類推理澎,最終完成計算并返回((((1+2)+3)+4)+5)的值。
>>> from functools import reduce
>>> seq = list(range(1,10))
>>> reduce(lambda x,y: x + y, seq)
45
filter()
Construct a list from those elements of iterable for which function returns true.
It takes one function and an iterable sequence. And we applied the function to every item of the iterable, it the function return True
, we add the item to filter object that will returned from filter function.
內(nèi)置函數(shù)filter()將一個單參數(shù)函數(shù)作用到一個序列上曙寡,返回該序列中使得該函數(shù)返回值為True的那些元素組成的filter對象糠爬,如果指定函數(shù)為None,則返回序列中等價于True的元素举庶。
>>> seq = ['foo', 'x41', '#nt']
>>> result = list(filter(lambda x: x.isalnum(), seq))
>>> result
['foo', 'x41']
>>> list(filter(None, [1, 2, 3, 0, 0, 4, 0, 5])) #指定函數(shù)為None
[1, 2, 3, 4, 5]
Lambda function:
In Python, anonymous function is a function that is defined without a name.
We use lambda functions when we require a nameless function for a short period of time.
Lambda functions are used along with built-in functions like filter(), map() etc.
double = lambda x: x * 2