Use of filter map reduce function

# filter("processing logic", "iterable object") The iterable object is processed logically in turn, if the value is true, it returns the value, and if the value is false, it does not return; 
li = [ ' testA ' , ' yerA ' , ' pp ' ]

print(list(filter(lambda x:x.endswith('A'),li)))   #['testa', 'yera']

 

#Write a function to implement the map function process: 
li = [1,2,3,4,5,6]   #If you need to add 1 to all the contents of li 
def map_test(func,array):
    ret = []
    for i in array:
        res = func(i)    # func = lambda x:x+1 ; func(i) is to execute the lambda function and pass the value of i to the lambda for processing 
        ret.append(res)
     return ret

result = map_test(lambda x:x+1,li)
print(result)


# The map function uses 
# map("processing logic", "iterable object") to pass the iterable object to the lambda in the for loop for processing. 
print (map( lambda x:x+1,li))    # <map object at 0x050A8310 >Generate an iterable object 
map_ret = list(map( lambda x:x+1,li))   # process the list into a list 
print (map_ret)       # [2, 3, 4, 5, 6, 7]


# The map function does not have to use a lambda function to process logic; it can also use its own defined logic to process 
def add(x):
     return x**2 
s = list(map(add,li))    #add is itself here The defined processing logic 
print (s)     # [1, 4, 9, 16, 25, 36]

 

 

# python 2 reduce can be used directly 
# python 3 from functools import reduce

from functools import reduce

def map_reduce(x,init=None):
    if init:
        ret = init
     else :
        ret = x.pop(0)
    for i in x:
        right = i + right
     return right
li = [1,2,3,10 ]
s = map_reduce(li)
print(s)

# reduce(function, sequence[, initial]) -> value function that takes two arguments to accumulate over the items of a sequence 
# accumulates a two argument function over the items of a sequence, left to right, to reduce the sequence to a single value. For example, reduce (lambda x, y: x + y, [1, 2, 3, 4, 5)) to compute ((((1 + 2) + (3) + 4) + 5). 
# If initial exists, It is placed before the items of the calculation sequence, and it is used as the default value when the sequence is empty. 
print (reduce( lambda x,y:x+y,li))      #The processing flow is to assign 1 in the list to x, and put 2 in the list is assigned to y, the first result is x = 1 + y=2, the second calculation is x = 3 + y=3 and so on 
print (reduce( lambda x,y:x+y,li,10 ))   #The processing flow is to assign the initial value 10 to x, assign 1 to y in the list, the first result is x = 11 + y=2, the second calculation x = 13 + y=3 and so on

Summarize:

    #map遍历序列中的每个元素,得到的结果是一个""列表"",列表的个数以及位置与原来的一样.

    #filter遍历序列中的每个元素,判断每个元素得到的布尔值,如果是Trun就保留,不然就丢弃.

  #reduce处理一个序列,然后把序列进行合并操作

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325007359&siteId=291194637