【Python】reduce

reduce(function, iterable[, initializer])
reduce has three parameters. The third parameter is the initial value and can be omitted.

  • function-function, has two parameters
  • iterable-iterable object
  • initializer-optional, initial parameters

The reduce() function accumulates the elements in the parameter sequence.
The function performs the following operations on all the 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 calculated with the third data using the function function, and finally a result is obtained.
for example:

def mysum(x,y):
	return x+y
reduce(mysum,[1,2,3,4,5])			#等于15
reduce(lambda x,y:x+y,[1,2,3,4,5])	#等于15
reduce(mysum,[1,2,3,4,5],6) 		#等于21

Guess you like

Origin blog.csdn.net/kz_java/article/details/114764799