Python 函数式编程

内置函数

map(function, iterable, ...) 
讲传入迭代器的值映射为另一个新值的列表
map还可以接受多个iterable作为参数,在第n次调用function时,将使用iterable1[n], iterable2[n], ...作为参数。

filter(function, iterable) 
这个函数的功能是过滤出iterable中所有以元素自身作为参数调用function时返回True或bool(返回值)为True的元素并以列表返回,与系列第一篇中的my_filter函数相同。

zip(iterable1, iterable2, ...) 
这个函数返回一个列表,每个元素都是一个元组,包含(iterable1[n], iterable2[n], ...)。 
例如:zip([1, 2], [3, 4]) --> [(1, 3), (2, 4)] 
如果参数的长度不一致,将在最短的序列结束时结束;如果不提供参数,将返回空列表。

使用方法:

print map(lambda x:x*x,range(1,5));#映射到新类型集合

print map(lambda x,y:x+y, range(0,5), range(10,15))#传递多个迭代器

print(reduce(lambda x,y:x+y,range(1,5))) #等价sum(r)

print filter(lambda x:x%2==0,range(11)) #筛选0-10中的素数

print zip([1, 2], [3, 4])

 

posted @ 2012-12-16 16:01  Bug山Bug海  阅读(162)  评论(0编辑  收藏  举报