Map, reduce and all these stuff

Continuing with a functional approach of python we take a look to the List functions. we will provide a little example for each one of this functions. This functions are map, reduce and filter.

Map

Map applies a function to each one of the elements of a sequence

secuence = list(range(0,10))
# secuence = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] f = lambda x: x + 1
map(f, secuence)
# result [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

Enter fullscreen mode Exit fullscreen mode

Filter

Filter reduces a secuence depending of a boolean function

secuence = list(range(0, 10))
# secuence = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] f = lambda x: x % 2 == 0
filter(f, secuence)
#result = [0, 2, 4, 6, 8] 

Enter fullscreen mode Exit fullscreen mode

Reduce

Reduce, is a operation that “reduces a list” apliying an operator

from functools import reduce
secuence = list(range(0, 10))
# secuence = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] f = lambda x, y: x + y
reduce(f,secuence)
# result = 45 # Using initial value, thanks to @magicleon94 reduce(f,secuence, 10)
# result = 55 

Enter fullscreen mode Exit fullscreen mode

原文链接:Map, reduce and all these stuff

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容