首页 > 编程语言 > 详细

python map、filter、reduce

时间:2016-02-08 17:25:47      阅读:138      评论:0      收藏:0      [点我收藏+]
Python has a few functions that are useful for this sort of “functional programming”: map, filter, and
reduce. 4 (In Python 3.0, these are moved to the functools module.) The map and filter functions are not
really all that useful in current versions of Python, and you should probably use list comprehensions instead.
You can use map to pass all the elements of a sequence through a given function:
>>> map(str, range(10)) # Equivalent to [str(i) for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You use filter to filter out items based on a Boolean function:
>>> def func(x):
... return x.isalnum()
...
>>> seq = ["foo", "x41", "?!", "***"]
>>> filter(func, seq)
[foo, x41]

For this example, using a list comprehension would mean you didn’t need to define the custom function:
>>> [x for x in seq if x.isalnum()]
[‘foo‘, ‘x41‘]
Actually, there is a feature called lambda expressions, 5 which lets you define simple functions in-line
(primarily used with map, filter, and reduce):
>>> filter(lambda x: x.isalnum(), seq)
[‘foo‘, ‘x41‘]
Isn’t the list comprehension more readable, though?
The reduce function cannot easily be replaced by list comprehensions, but you probably won’t need its
functionality all that often (if ever). It combines the first two elements of a sequence with a given function,
combines the result with the third element, and so on until the entire sequence has been processed and a sin-
gle result remains. For example, if you wanted to sum all the numbers of a sequence, you could use reduce
with lambda x, y: x+y (still using the same numbers): 6
>>> numbers = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
>>> reduce(lambda x, y: x+y, numbers)
1161
Of course, here you could just as well have used the built-in function sum.

 

python map、filter、reduce

原文:http://www.cnblogs.com/zhuweiblog/p/5185041.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!