reduce(fun,seq)函数用于将在其参数中传递的特定函数应用于传递的序列中提到的所有列表元素。此函数在“functools”模块中定义。
工作方式:
- 第一步,选择序列的前两个元素并获得结果。
- 下一步是对先前获得的结果应用相同的函数,并且紧随第二个元素之后的数字将被再次存储。
- 继续此过程,直到容器中没有剩余元素为止。
- 返回的最终结果将返回并打印在控制台上。
# python code to demonstrate 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))
# 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 sum of the list elements is:17 The maximum element of the list is:6
Using Operator Functions
reduce()也可以与运算符函数结合使用,以实现与lambda函数相似的函数,并使代码更具可读性。
# python code to demonstrate working of reduce()
# using operator functions
# importing functools for reduce()
import functools
# importing operator for operator functions
import operator
# initializing list
lis = [ 1 , 3, 5, 6, 2, ]
# using reduce to compute sum of list
# using operator functions
print ("The sum of the list elements is:",end="")
print (functools.reduce(operator.add,lis))
# using reduce to compute product
# using operator functions
print ("The product of list elements is:",end="")
print (functools.reduce(operator.mul,lis))
# using reduce to concatenate string
print ("The concatenated product is:",end="")
print (functools.reduce(operator.add,["geeks","for","geeks"]))
输出量
The sum of the list elements is:17 The product of list elements is:180 The concatenated product is:geeksforgeeks
reduce()和accumulate()
reduce()和accumulate()均可用于计算序列元素的总和。但是这两者在实现方面都有差异。
- reduce()在“functools”模块中定义,accumulate()在“itertools”模块中定义。
- reduce()存储中间结果,并且仅返回最终的求和值。而accumulate()返回包含中间结果的列表。返回的列表的最后一个数字是列表的总和。
- reduce(fun,seq)将函数作为第一参数,将序列作为第二参数。相反,accumulate(seq,fun)将序列作为第一个参数,将函数用作第二个参数。
# python code to demonstrate summation
# using reduce() and accumulate()
# importing itertools for accumulate()
import itertools
# importing functools for reduce()
import functools
# initializing list
lis = [ 1, 3, 4, 10, 4 ]
# priting summation using accumulate()
print ("The summation of list using accumulate is:",end="")
print (list(itertools.accumulate(lis,lambda x,y:x+y)))
# priting summation using reduce()
print ("The summation of list using reduce is:",end="")
print (functools.reduce(lambda x,y:x+y,lis))
输出:
The summation of list using accumulate is:[1, 4, 8, 18, 22] The summation of list using reduce is:22
相关用法
注:本文由纯净天空筛选整理自 reduce() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。