首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

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

2012-08-27 
python 如此灵活的使用filter, map, reduce, sumFunctional Programming ToolsThere are three built-in f

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.

热点排行