python: filter, map, reduce, lambda

filter built-in function

filter(f,sequence)

filter can apply the function f to each element of sequence. If return is true the element will be returned and re-organized to be a new sequence. The type of new sequence can be list/tuple/string, this depends on the input sequence type.

>>> l=[1,2,3,4,5]
>>> f = lambda x: True if x%2 == 0 else False
>>> filter(f,l)
[2, 4]
>>> t=(1,2,3,4,5)
>>> filter(f,t)
(2, 4)

map built-in function

map(f, sequence)

map will apply f to each element of sequence. The result will be returned to be a new list(Unless filter, the return will always a list).

>>> f= lambda y : y*2
>>> l=[1,2,3]
>>> t=(1,2,3)
>>> map(f,l)
[2, 4, 6]
>>> map(f,t)
[2, 4, 6]

reduce() built-in function

reduce(f, sequence, start_value)

reduce apply f to sequence by the order of the sequence. If there is a start_value, this one will be called first.

>>> l = [1,2,3,4,5,6,7,8,9]
>>> f = lambda x,y : x+y
>>> reduce(f,l)
45
>>> reduce(f,l, 20)
65

posted on 2016-11-07 12:34  kramer  阅读(132)  评论(0编辑  收藏  举报

导航