describe
The reduce() function accumulates the elements in the parameter sequence.
The function performs the following operations on all data in a data set (linked list, tuple, etc.): use the function function (with two parameters) passed to reduce to operate on the first and second elements in the set, and get The result is then combined with the third data to use the function function, and finally a result is obtained.
grammar
reduce() function syntax:
reduce(function, iterable[, initializer])
return value
Returns the result of the function evaluation.
The old method, first give a requirement, calculate a sum of the numbers in the following list
#Writing with function num_l = [1,2,3,100] def reduce_test(array): res = 0 for num in array: res+=num return res print reduce_test(num_l)
The problem with the above writing method is that the calculation method is dead, so a separate function must be written.
num_l = [1,2,3,100] def sumadd (x, y): res=x+y return res def reduce_test(func,array): res = 0 for num in array: res=func(res,num) return res print reduce_test(sumadd,num_l)
Finally, combine the reduce function with the anonymous function
print reduce(lambda x,y:x+y,num_l)