欢迎访问宙启技术站
智能推送

Python reduce函数的概念和实际应用

发布时间:2023-05-23 05:12:33

Python中的reduce()函数是一个在给定的可迭代对象(列表,元组等)中使用给定函数对其所有元素进行聚合的高阶函数。它需要一个可调用对象和一个可迭代对象作为参数,并对给定的可迭代对象中的所有元素应用给定的函数,以产生一个单一值作为其输出。reduce()函数的简化语法如下。 

reduce(function, iterable[, initializer])

此处,function参数是一个可调用函数,通常是lambda函数或更常规的函数。接下来的iterable参数是一个可迭代对象,可以是列表、元组或其他可迭代对象。最后,initializer参数是在转换开始之前用作初始值的可选值。

在Python中,reduce()函数的实际应用范围非常广泛,例如,对于一些聚合函数,如求和,乘积和最大值等。以下是一些使用reduce函数的实际应用的示例:

1.对列表中的元素求和:

下面是通过reduce函数对一个列表中的元素进行求和的示例。

# Python program to show working

# of reduce()

# importing functools for reduce()

import functools 

# initializing list

lis = [ 1 , 3, 5, 6, 2, ] 

# using reduce to compute sum of list

print ("The sum of the list elements is : ",end="") 

print (functools.reduce(lambda a,b : a+b,lis)) 

这将产生以下结果。

The sum of the list elements is : 17

2. 列表元素的乘积:

下面是一个使用reduce函数计算给定列表元素乘积的示例。

# Python program to show working

# of reduce()

# importing functools for reduce()

import functools 

# initializing list

lis = [ 1 , 3, 5, 6, 2, ]

# using reduce to compute sum of list

print ("The product of the list elements is : ",end="") 

print (functools.reduce(lambda a,b : a*b,lis)) 

这将产生以下结果。

The product of the list elements is : 180

3.从列表中查找最大值:

以下是一个使用reduce函数从列表中获取最大元素的示例。

# Python program to show working

# of reduce() 

# importing functools for reduce()

import functools 

# initializing list 

lis = [ 1 , 3, 5, 6, 2, ]

# using reduce to compute maximum element from list

print ("The maximum element of the list is : ",end="") 

print (functools.reduce(lambda a,b : a if a > b else b,lis))

这将产生以下结果。

The maximum element of the list is : 6

4. 列表中的分数求和:

以下是一个使用reduce函数计算给定列表中所有分数的求和的示例。

# Python program to show working

# of reduce()

 

# importing functools for reduce()

import functools 

 

# initializing list

lst = [(1, 2), (3, 4), (10, 6), (8, 11), (15, 3)]

 

# using reduce to compute sum of list

print("The product of the list elements is : ", end="")

print(functools.reduce(lambda x, y: (x[0]*y[1] + y[0]*x[1], x[1]*y[1]), lst))