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.
内置函数map()可以将一个函数依次映射到序列或迭代器对象的每个元素上,并返回一个可迭代的map对象作为结果,map对象中每个元素是原序列中元素经过该函数处理后的结果,该函数不对原序列或迭代器对象做任何修改。
list(map(add5, range(10))) #把单参数函数映射到一个序列的所有元素
[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.
标准库functools中的函数reduce()可以将一个接收2个参数的函数以迭代累积的方式从左到右依次作用到一个序列或迭代器对象的所有元素上,并且允许指定一个初始值。例如,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.
内置函数filter()将一个单参数函数作用到一个序列上,返回该序列中使得该函数返回值为True的那些元素组成的filter对象,如果指定函数为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])) #指定函数为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