Use of map, filter, reduce

Python built-in functions map and filter both perform corresponding operations on a sequence, map is a custom mapping for each element, and filter is to filter each element of the sequence.

The filter (fun, sequence)
parameter fun can be a custom function name or a lambda function. The parameter sequence is a sequence, which can be a list, tuple, or string. The function makes conditional judgments on each element of the sequence and returns all True elements. The returned object is an iterator. As follows:

a = [1,2,3,4,5,6,7,8,9]
def fun(a):
    return a% 2 ==0
res = filter(lambda x:x>5,a)
print(res )
print(list(res))
res1 = filter(fun,a)
print(res1)
print(list(res1))
<filter object at 0x0031FA70>
[6, 7, 8, 9]
<filter object at 0x0032D8D0>
[2 , 4, 6, 8] The
map
function and filter on the map (fun, sequence) parameters are the same. The difference between them is that the function is a mathematical substitution for each element, rather than a conditional judgment. This function also returns an iterator. As follows:

a = [1,2,3,4,5,6,7,8,9]
b = [2,3,4,5,6,7,8,9,0]
def fun(a):
    return a +1
res = map(lambda x,y:x+y,a,b)
print(res)
print(list(res))
res1 = map(fun,a)
print(res1)
print(list(res1))
< map object at 0x03A5D8D0>
[3, 5, 7, 9, 11, 13, 15, 17, 9]
<map object at 0x03AFC110>
[2, 3, 4, 5, 6, 7, 8, 9, 10]
reduce The (fun, sequence)
parameter is the same as the above two. Its function is to compress a sequence to get a value. But reduce was a built-in function in python2, and moved to the functools module in python3, so you need from functools import reduce before using it. The difference with the above is that this function returns a value instead of an iterator, and the fun function must pass in two parameters. As follows:

from functools import reduce
a = [1,2,3,4,5,6,7,8,9]
def fun(a,b):
    return a*b
 
res = reduce(lambda x,y:x+y,a)
print(res)
res1 = reduce(fun,a)
print(res1)
45
362880

Guess you like

Origin blog.csdn.net/sichuanpb/article/details/114980613