Correct Usage of Several Common Functions in python lambda and filter and map and reduce

  • 2021-12-12 09:01:35
  • OfStack

Directory 1 lambda2 filter3 map4 reduce5 used in conjunction

lambda/filter/map/reduce These functions will definitely be used in the interview. This article mainly introduces the usage of these functions.

1 lambda

Anonymous function, used as follows:


# lambada  Parameter , Parameter , Parameter  :  The returned expression 


Example 1:


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


Example 2:


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

2 filter

filter (function, sequence): Right sequence In item Execute in turn function(item) The result of the execution is True Adj. item Form 1 filter Object (iterable) depending on sequence The type of the.

Example:


'''
 No one answers the problems encountered in study? Xiaobian created 1 A Python Learning and communication group: 531509025
 Looking for like-minded friends and helping each other , There are also good video learning tutorials and PDF E-books! 
'''
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): Right sequence In item Execute in turn function(item) See the implementation results to form 1 map Object, which can be iterated, returns.

Example:


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

python3 In, reduce Has been removed from the global namespace, and needs to be removed from the functiontools Import into.

reduce (function, sequence, starting_value) sequence In item Sequential iterative call function , if there is starting_value Can also be used as an initial value.

Example:


'''
 No one answers the problems encountered in study? Xiaobian created 1 A Python Learning and communication group: 531509025
 Looking for like-minded friends and helping each other , There are also good video learning tutorials and PDF E-books! 
'''
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!


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, isn't it very simple?


Related articles: