The function of lambda-filter-map-reduce in python

lambda : Anonymous function , which makes the function more concise, and sometimes has infinite uses;

How to use: variable directly after lambda, colon after face change, expression after colon, the calculation result of the expression is the return value of this function

Note: Although a lambda function can take any number of arguments and return the value of a single expression, a lambda function cannot contain commands and contain no more than one expression. If you need something more complex, you should define a function.

eg:

 filter: filter

eg:

numbers =range(-5,5)
print(list(filter(lambda x:x>0,numbers)))

Output result: [1,2,3,4]

is equivalent to the following code                        

[x for x in numbers if x > 0]

 map: Mapping, map is a built-in function of Python, its basic format is: map(func, seq)

For map, you should mainly understand the following points:

1. For each element in the iterable object, use the fun method in turn (in fact, it is essentially a for loop).

2. Return all the results to a map object, which is an iterator.

eg:

list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3=list(map(lambda x,y: x + y,list1,list2))
print(list3)

Output result: [6, 8, 10, 12]

reduce: The function acts on the sequence. The first parameter of the reduce function is a function, and the second parameter is an object of the sequence type. The function is applied to the sequence in order from left to right.

eg:

from functools import reduce
a=reduce(lambda x,y:x+y,[1,2,3,4,5])
print(a)

Output result: 15

Guess you like

Origin blog.csdn.net/Darin2017/article/details/121626434