Learning Python (4) -- function-oriented programming

Source: Internet
Author: User
It can be said that modern Program Languages are more or less affected by the lisp family, and python is no exception. Because I used to know some knowledge about lisp (scheme), I feel that python has learned quite like this.

Filter (Function,Sequence) You can filter out the elements that meet the function conditions from sequence (by listing, tuple, and string) (the function return type is required to be boolean ). For example:
>>> Def f (x): Return X % 2! = 0 and X % 3! = 0
...
>>> Filter (F, range (2, 25 ))
[5, 7, 11, 13, 17, 19, 23]

Map (Function,SequenceIn turn, each element in the sequence is substituted into the function for calculation. For example:
>>> Def cube (x): Return x * x
...
>>> Map (cube, range (1, 11 ))
[1, 8, 27, 64,125,216,343,512,729,100 0]
The map function can also be used with multiple parameters, but must be consistent with the first parameter (function:
>>> Seq = range (8)
>>> Def add (x, y): Return x + y
...
>>> Map (ADD, seq, SEQ)
[0, 2, 4, 6, 8, 10, 12, 14]

Reduce (Function,Sequence. It first substitutes the first two elements of sequence into the function, and then the result and the third element into the function ...... Until the last value is obtained. Let's explain it using examples:
>>> Def sum (SEQ ):
... Def add (x, y): Return x + y
... Return reduce (ADD, seq, 0)
...
>>> Sum (range (1, 11 ))
55
>>> Sum ([])
0
In the python document, we finally pointed out that we should not use this method to achieve the sum. Because this operation is very common, Python provides a built-in function: sum (Sequence)

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.