Python Higher order function map (), filter (), reduce ()

Source: Internet
Author: User

The map () function, which receives two parameters, one is a function, the other is a sequence, and map () acts on each element of the sequence in turn, and returns the result as a new sequence;

AA = [1, 2, 3, 4, 5]print ("", List (map (Lambda a:a * A, aa)))#Map-result = [1, 4, 9, 16, 2 5]       

The filter () function, which receives two parameters, one is a function, the other is a sequence, and filter () applies the passed function to each element sequentially, depending on whether the return value is true or false, whether the element is persisted or discarded, and the resulting sequence is a subset of all return values true;

AA = [1, 2, 3, 4, 5]print ("", List (filter (lambda a:a >=3, aa))#Filter-result = [3, 4, 5]       

The reduce () function, which acts on a sequence, must receive two parameters, where the reduce () function accumulates the result and the next element of the sequence, and the reduce () function returns only the result of the value, not the sequence. In Python3, the reduce () function is moved to the Functools package.

Import reduceaa= [1,2,3,4,5]print ("", Reduce (lambda A, B: (A * b), aa))#  Reduce-result =        

Python Higher order function map (), filter (), reduce ()

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.