python 3.0以后, reduce已经不在built-in function里了, 要用它就得from functools import reduce.

reduce的用法

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.

 

意思就是对sequence连续使用function, 如果不给出initial, 则第一次调用传递sequence的两个元素, 以后把前一次调用的结果和sequence的下一个元素传递给function. 如果给出initial, 则第一次传递initial和sequence的第一个元素给function.

from functools import reduce  
reduce(lambda x,y: x+y, [1, 2, 3])  
输出 6  
reduce(lambda x, y: x+y, [1,2,3], 9)  
输出 15  
reduce(lambda x,y: x+y, [1, 2, 3], 7)  
输出 13  

  

*functool标准库还有很多功能,可以参考网上的资料

相关文章:

  • 2021-05-31
  • 2021-08-01
  • 2021-08-30
  • 2022-01-02
  • 2021-12-27
  • 2021-12-19
  • 2022-03-02
猜你喜欢
  • 2022-12-23
  • 2021-10-10
  • 2022-12-23
  • 2021-11-29
  • 2021-06-23
  • 2021-05-22
  • 2021-11-06
相关资源
相似解决方案