Functional use in Python

Source: Internet
Author: User

For linked lists, there are three built-in functions that are useful: filter (), map (), and reduce ().

filter(function, sequence)Returns an sequence (sequence) that includes the elements that return a value of true after all calls in a given sequence function(item) (the same type is returned, if possible). If the sequence (sequence) is a str,unicode or a tuple, the return value must be the same type, otherwise it is always list. For example, the following program can calculate a sequence that is divisible by 3 and 5:

def F (x):    return x 3 = = 0 and x 5 = = 0print filter (F,range (2,100))

[15, 30, 45, 60, 75, 90]

map(function, sequence)Each element is called in turn function(item) and the return value is returned as a linked list. For example, the following program outputs the elements in the list 3 times:

def Word (x):    return x*3words = [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ']print map (word,words)
[' 111 ', ' 222 ', ' 333 ', ' 444 ', ' 555 ', ' 666 ']

You can pass in more than one sequence, and the function must have a corresponding number of arguments, which, in turn, invoke the function with the corresponding elements on each sequence (if some sequences are shorter than others, use None them instead). If None a function is passed in, the parameter is returned as an alternative. For example:

SEQ1 = Range (8= range (9,17)def  Add (x, y    ):return x+y Print map (ADD,SEQ1,SEQ2) [9, 11, 13, 15, 17, 19, 21, 23]

reduce(function, sequence)Returns a single value, which is constructed by invoking the function functions first with the first two elements of the sequence, then invoking the return value and the third argument, and sequentially executing. For example, the following program calculates the sum of integers 1 to 10:

def Add (x, y    ): return x+yprint reduce (Add,range (1,11))

55

Functional use in Python

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.