# [偷懒：）]Functional Programming Tools

### 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 f(x): return x % 2 != 0 and x % 3 != 0...>>> filter(f, range(2, 25))[5, 7, 11, 13, 17, 19, 23]

"map(function, sequence)" calls function(item) for each of the sequence's items and returns a list of the return values. For example, to compute some cubes:

>>> def cube(x): return x*x*x...>>> map(cube, range(1, 11))[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

More than one sequence may be passed; the function must then have as many arguments as there are sequences and is called with the corresponding item from each sequence (or None if some sequence is shorter than another). For example:

>>> seq = range(8)>>> def add(x, y): return x+y...>>> map(add, seq, seq)[0, 2, 4, 6, 8, 10, 12, 14]

"reduce(function, sequence)" returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on. For example, to compute the sum of the numbers 1 through 10:

>>> def add(x,y): return x+y...>>> reduce(add, range(1, 11))55

If there's only one item in the sequence, its value is returned; if the sequence is empty, an exception is raised.

A third argument can be passed to indicate the starting value. In this case the starting value is returned for an empty sequence, and the function is first applied to the starting value and the first sequence item, then to the result and the next item, and so on. For example,

>>> 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.

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
08-20
02-27
02-27
02-27
02-27
02-27

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。