python map & filter & reduce

map, filter, reduce 是函数式编程的函数, 不再需要循环分支使得代码更加简洁。map/reduce 和google的map/reduce功能是类似的, filter有些类似shuffle, 当然shuffle更多的工作是将相同的key放到同一个reduce计算中

map

map(function_to_apply, list_of_inputs)

例如:

items = [1,2,3,4,5]
squared = []
for i in items:
    squared.append(i**2)
print(squared)

<=> 等价于

items = [1,2,3,4,5]
squared = list(map(lambda x: x**2, items))
print(squared)

filter

filter(function_to_apply, list_of_inputs)

接着上面的代码继续

less_than_ten=[]
for i in squared:
    if i < 10:
        less_than_ten.append(i)
print(less_than_ten)

<=> 等价于

less_than_ten=[]
less_than_ten = list(filter(lambda x: x<10, squared))
print(less_than_ten)

reduce

reduce(function_to_apply, list_of_inputs)

和上面两个函数不同, reduce将进行迭代合并操作

product = 0
for i in less_than_ten:
    product = product + i
print(product)

<=> 等价于

from functools import reduce
product = 0
product = reduce((lambda x,y:x+y), less_tan_ten)
print(product)

参考及引用

https://book.pythontips.com/en/latest/map_filter.html
Photo by Andy Vu from Pexels

Comments are closed.