【map】
map()
Function takes two parameters, a function, a is Iterable
, map
to pass successively to the function of each element of the sequence, and the result as a new Iterator
return.
Calculating a function of the input value from 1 to 10, and returns an array
def f(x):
return x*x
L=list(range(1,11))
print (list(map(f,L)))
operation result:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[Finished in 0.7s]
The first letter is converted to uppercase, lowercase rest, for example:
def normalize(name):
return name.capitalize()
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
【reduce】
A role in the function of a sequence [x1, x2, x3, ...]
, the function must receive two parameters, reduce
the results and continues to the next element in the sequence is calculated as the accumulator
from functools import reduce
def f(x,y):
return x*10+y
L=[1, 3, 5, 7, 9]
print (reduce(f,L))
operation result:
13579
【filter】
And map()
the like, filter()
also receives a function and a sequence. And map()
the difference is, filter()
the function passed successively to each element, based on the returned value True
is False
decided to keep or discard the element.
Determining a string of consecutive characters selected as three numbers and three or more numbers, and printed in the form of an array
Example:
import re
s="37eu3rh45666hjfhdjhf9444njdhfjr445"
def f(x):
return len(x)>=3
L=[]
L=re.findall('[0-9]+',s)
print (list(filter(f,L)))
operation result:
['45666', '9444', '445']
[Finished in 0.3s]
【sorted】
sorted()
Function you can sort the list
sorted()
A higher order function is a function that can receive a key
function to implement custom sorting, such as sorting by the absolute value of:
sorted ([36, 5, -12, 9, -21], key = abs, reverse = True) #reverse represented reverse display
operation result:
[36, -21, -12, 9, 5]
[Finished in 0.5s]
According to sort tuples
students = [('B', 75), ('A', 92), ('B', 66), ('L', 88)]
print(sorted(students, key=lambda t: t[1]))
print(sorted(students, key=lambda t: t[1]), reverse=True))
operation result:
[('B', 66), ('B', 75), ('L', 88), ('A', 92)]
[('A', 92), ('L', 88), ('B', 75), ('B', 66)]
[Finished in 0.3s]