读书人

python 如此灵活的使用filter, 地图,

发布时间: 2012-08-27 21:21:57 作者: rapoo

python 如此灵活的使用filter, map, reduce, sum
Functional Programming Tools

There are three built-in functions that are very useful when used with lists: filter(), map(), and reduce().

filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true. If sequence is a string or tuple, the result will be of the same type; otherwise, it is always a list. For example, to compute some primes:

>>> def sum(seq):...     def add(x,y): return x+y...     return reduce(add, seq, 0)...>>> sum(range(1, 11))55>>> sum([])0

Don’t use this example’s definition of sum(): since summing numbers is such a common need, a built-in function sum(sequence) is already provided, and works exactly like this.

New in version 2.3.

读书人网 >perl python

热点推荐