An interesting part of Python: reduce, map, filter, and pythonreduce

Source: Internet
Author: User
Tags iterable

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.