Python-Functional Programming (1)

Source: Internet
Author: User

Higher order functions: functions that accept functions as arguments are higher-order functions

function as a parameter to find the absolute value.
def add (x, Y, f):
return f (x) +f (y)
Add ( -5, 9, ABS)

1). Map () is a Python built-in high-order function that receives a function f and a list, and then, by putting the function f on each element of the list in turn, gets a new list and returns.
For example, for list [1, 2, 3, 4, 5, 6, 7, 8, 9], you can use the map () function if you want to square each element of the list:
def f (x):
Return x*x
Print (Map (f, [1, 2, 3, 4, 5]))

Task: Assume that the user entered the English name is not standard, not according to the first letter capitalization, followed by the letter lowercase rules, use the map () function, a list (including a number of nonstandard English names) into a list containing the canonical English name:
Input: [' Adam ', ' LISA ', ' BarT ']
Output: [' Adam ', ' Lisa ', ' Bart ']
def formart_name (name):
Name = Name.lower (). Capitalize ()
return name
Print (Map (formart_name, [' Adam ', ' LISA ', ' BarT ')]

2). The reduce () function is also a high-order function built into Python. The reduce () function receives a parameter similar to map (), a function f, a list, but behaves differently from map (), and reduce () the incoming function f must receive two parameters, and reduce () calls function f repeatedly on each element of the list and returns the final result value.
The Python3 is placed in the Fucntools module with the first introduction: From Functools import reduce
def f (x, Y):
return x + y
Reduce (f, [1, 3, 5, 7, 9]) sums all the elements of the list #实际上是对

Reduce () can also receive a 3rd optional parameter as the initial value of the calculation. If you set the initial value to 100, the calculation:
Reduce (f, [1, 3, 5, 7, 9],) #结果将变为125

Python-Functional Programming (1)

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.