Correct usage of several common functions in Python – lambda / filter / map / reduce

Time:2022-5-24
catalogue

lambda/filter/map/reduceThese functions will certainly be used in the interview. This article mainly introduces the usage of these functions.

1 lambda

Anonymous functions are used as follows:

?
1
#Lambada parameter, parameter, parameter: returned expression

Example 1:

?
1
2
f = lambda x, y: x * y
print(f(2, 3))    # 6

Example 2:

?
1
2
r = (lambda x, y: x+y)(1, 2)
print(r)          # 3

2 filter

filter(function, sequence):yessequenceMediumitemSequential executionfunction(item), the execution result isTrue ofitemForm afilterObject (iteratable) (depending onsequence(type of).

Example:

?
1
2
3
4
5
6
7
8
9
'''
No one answers the problems encountered in learning? Xiaobian created a python learning exchange group: 531509025
Look for like-minded friends to help each other. There are also good video learning tutorials and PDF e-books in the group!
'''
def gt_5(x):
    return x > 5
 
r = filter(gt_5, range(10))
print(list(r))      # [6, 7, 8, 9]

3 map

map(function, sequence):yessequenceMediumitemSequential executionfunction(item)See the implementation results to form amapObject (iteratable) returns.

Example:

?
1
2
3
4
5
def mysum(x, y):
    return x + y
 
r = map(mysum, range(5), range(5, 10))
print(list(r))      # [5, 7, 9, 11, 13]

4 reduce

python3In,reduceHas been removed from the global namespace and needs to be removed from thefunctiontoolsImport from.

reduce(function, sequence, starting_value):yessequenceMediumitemSequential iterative callfunction, if anystarting_value, can also be used as an initial value.

Example:

?
1
2
3
4
5
6
7
8
9
10
'''
No one answers the problems encountered in learning? Xiaobian created a python learning exchange group: 531509025
Look for like-minded friends to help each other. There are also good video learning tutorials and PDF e-books in the group!
'''
def mysum(x, y):
    return x + y
 
from functools import reduce
r = reduce(mysum, range(10))
print(r)     # 45

5 combined use

Example:Calculate 1+ 2!+…+ 10!

?
1
2
3
4
5
6
def factorial(n):
    if n == 1:
        return 1
    return n*factorial(n-1)
r = reduce(lambda x, y: x + y, map(factorial, range(1, 11)))
print(r)    # 4037913

This is the usage of several functions. Is it very simple?

This is the end of this article about the correct usage of several common functions in Python – lambda / filter / map / reduce, and more about the correct usage of common functions in Pythonlambda filter map reducePlease search the previous articles of developeppaper or continue to browse the relevant articles below. I hope you will support developeppaper in the future!