标签:
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.
标签:
原文地址:http://www.cnblogs.com/zhuweiblog/p/5185041.html