These functions of lambda/filter/map/reduce will definitely be used in interviews. This article mainly introduces the usage of these functions.
1.lambda
Anonymous function, the usage is as follows:
# lambada 参数,参数,参数 : 返回的表达式
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): sequentially execute function(item) on the items in the sequence, and return the items whose execution result is True to form a filter object (iterable) (depending on the type of sequence).
Example:
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): execute function(item) in sequence on the items in the sequence, see the execution result to form a map object (iterable) and return.
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
In python3, reduce has been removed from the global namespace and needs to be imported from functiontools.
reduce(function, sequence, starting_value)
: Call the function iteratively on the items in the sequence. If there is starting_value
, it can also be used as the initial value.
Example:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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 how a few functions are used. Isn't it simple?