One, Python-map () function
1. First, learn the string case conversion in Python:
s = ' HEllo PYthon '
Print S.upper () convert all to uppercase
Print S.lower () convert all to lowercase
Print s.capitalize () uppercase, remaining lowercase
Print s.title () All words capitalized, remaining lowercase
2. Map () function:
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.
Exercise: Except for the first letter, the remaining lowercase
Input: [' Adam ', ' LISA ', ' BarT ']
Output: [' Adam ', ' Lisa ', ' Bart ']
Answer:
def format_name (s):
Return S.title ()
Print map (format_name, [' Adam ', ' LISA ', ' BarT ')
The reduce function: thereduce () 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.
Practice:
Python has built-in sum function sum (), but there is no quadrature function, please use Recude () to calculate the product:
Input: [2, 4, 5, 7, 12]
Output: Results of 2*4*5*7*12
def prod (x, y):
Return X*y
Print reduce (prod, [2, 4, 5, 7, 12])
Iii. the filter () function in Python
The filter () function is another useful high-order function built into Python, and the filter () function receives a function f and a list, the function of which is to judge each element, returning TRUE or False,filter () automatically filters out non-conforming elements based on the result of the decision, and returns a new list that is composed of qualifying elements.
Practice:
Filter () to 1~100 that the square root is an integer number, i.e. the result should be:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Answer:
Import Math
def IS_SQR (x):
return math.sqrt (x)% 1 = = 0
Print filter (IS_SQR, Range (1, 101))
Python-Functional programming