Map、Filter和Reduce函数(Python)
Map
map(function_to_apply, list_of_inputs)
设有以下代码:
>>> items = [1, 2, 3, 4, 5]
>>> squared = []
>>> for i in items:
... squared.append(i**2)
...
>>> squared
[1, 4, 9, 16, 25]
这段代码实现的功能用map函数可以两行完成:
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
高级一点地,可以用一列函数作为输入:
def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = list(map(lambda x: x(i)+1, funcs))
print(value)
>>>
[1, 1]
[2, 3]
[5, 5]
[10, 7]
[17, 9]
Filter
Filter creates a list of elements for which a function returns true.
>>> number_list = range(-5,5)
>>> less_than_zero = list(filter(lambda x: x<0, number_list))
>>> print(less_than_zero)
[-5, -4, -3, -2, -1]
经过_filter_函数_过滤_,条件判断为真的结果的存入list。另外值得注意的地,_filter_是_built-in_函数,运行速度更快。
Reduce
Reduce is a really useful function for performing some computation on a list and returning the result. It applies a rolling computation to sequential pairs of values in a list.
>>> from functools import reduce
>>> product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
>>> product
24