An interesting part of Python: reduce, map, filter, and pythonreduce
I have read a series of articles on Python functional programming today. The address is here:
Http://www.cnblogs.com/huxi/archive/2011/06/24/2089358.html
It mentions four built-in iteration functions: reduce, map, filter, and zip. Zip is used to iterate multiple iterators at the same time. We will not discuss it here. This article mainly discusses the remaining three items.
One interesting thing I found is that the three remaining functions, reduce, map, and filter, can be converted to each other. For example, based on reduce, map and filter functions can be implemented as follows:
1 def _map(func, iterable):2 return reduce(lambda lst, x: lst.append(func(x)) or lst, iterable, [])3 4 def _filter(func, iterable):5 return reduce(lambda lst, x: lst.append(x) or lst if func(x) else lst, iterable, [])
The above or operator is used for process control, lst. append (x) or lst will add x to lst, and then return lst, because lst. append (x) returns None.
Other functions can be implemented based on map or filter, but they are not as concise as map and filter implemented based on reduce. The pasting implementation is as follows:
This is to implement reduce and filter Based on map:
1 #map as the base 2 3 def _reduce(func, iterable, init): 4 result = init 5 map(lambda x: result = func(result, x), iterable) 6 return result 7 8 def _filter(func, iterable): 9 lst= []10 map(lambda x: lst.append(x) if func(x), iterable)11 return lst
This is based on the filter to implement the other two:
1 #filter as the base 2 3 def _reduce(func, iterable, init): 4 result = init 5 filter(lambda x: result = func(result, x), iterable) 6 return result 7 8 def _map(func, iterable): 9 lst = []10 filter(lambda x: lst.append(func(x)), iterable)11 return lst
They are not very interesting.