Python中的reduce()怎么使用(代码示例)

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

使用运算符功能
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 : lsbin

【Python中的reduce()怎么使用(代码示例)】reduce()vs 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

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

    推荐阅读