map:
Map function: The map function accepts two parameters, one is the name of the function and the other is an iterative object. Through iteration, the objects in the iteratable object are passed into the function in turn, and the new iteratable object is returned after completion.
Examples of usage:
#Get the square value of [2,4,6,7,8] in turn
def f(x):
return x*x
print(list(map(f,[2,4,6,7,8]))) #[4, 16, 36, 49, 64]
#Capitalize the initial letters of adam, LISA and barT, and lower case the other words:
def Normalize(name):
return name[0].upper()+name[1:len(name)].lower()
L1 = ['adam', 'LISA', 'barT']
L2=list(map(Normalize,L1))
print(L2) #['Adam', 'Lisa', 'Bart']
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
reduce:
Reduc function: Similar to map() function, it also acts on a function in a set of iterative objects. The difference is that the function required by reduce must pass in two parameters and accumulate the result of the previous one to the next element.
Examples of usage:
#Find the value of 1+2+3+...+100
from functools import reduce
def f(x,y):
return x+y
list=[]
for i in range(1,101):
list.append(i)
l=reduce(f,list)
print(l) # 5050
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
filter:
About filter: filter is similar to the two above, except that the filter function returns a Boolean value to determine whether the element is retained or discarded.
Examples of usage:
#Output all prime numbers between 1 and 100:
import math
def f(x):
if(x==1):
return False
elif(x == 2):
return True
flag=0
for i in range(2,int(math.sqrt(x)+1)):
if(x%i==0):
flag+=1
if(flag>=1):
return False
else:
return True
list=[]
for i in range(1,101):
list.append(i)
l=filter(f,list)
print l #[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
sorted:
Sorted function: literally, we all know that sort means sort, so sorted is used to sort.
Examples of usage:
#One parameter:
#Sort [- 2, 8, - 4, 7, - 9, 2, 6, 5]
list=[-2,8,-4,7,-9,2,6,5]
l=sorted(list)
print(l) #[-9, -4, -2, 2, 5, 6, 7, 8]
#Two parameters
#Sort [- 2, 8, - 4, 7, - 9, 2, 6, 5] by absolute value
list=[-2,8,-4,7,-9,2,6,5]
l=sorted(list,key=abs)
print(l) #[-2, 2, -4, 5, 6, 7, 8, -9]
#Three parameters
#Inverse ordering of [-2,8,-4,7,-9,2,6,5] by absolute values
list=[-2,8,-4,7,-9,2,6,5]
l=sorted(list,key=abs,reverse=True)
print(l) #[-9, 8, 7, 6, 5, -4, -2, 2]