python map、filter、reduce
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.
?
轉載于:https://www.cnblogs.com/zhuweiblog/p/5185041.html
總結
以上是生活随笔為你收集整理的python map、filter、reduce的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: STL数据结构
- 下一篇: mysql查最大字符串