The Reduce Function in Python

  • 时间:2020-09-13 14:33:25
  • 分类:网络文摘
  • 阅读:150 次

In Python, the reduce() function is declared in the functools. And it has the following function signature:

1
reduce(method, data, initial_value);
reduce(method, data, initial_value);

The reduce() function will iterate over the data array (or list), and accumulate a value (set to initial_value first) using the given function which has the following signature:

1
2
def reducer_method(accumulated_value, current_value):
   pass
def reducer_method(accumulated_value, current_value):
   pass

For example, to sum up all the values from 1 to 100, you can use this:

1
2
from functools import reduce
reduce(lambda s, cur: s + cur, range(101), 0)
from functools import reduce
reduce(lambda s, cur: s + cur, range(101), 0)

As we can see, the reducer function for sum is passed as a lambda function, which is essentially the same as:

1
2
def reducer_sum(s, cur):
   return s + cur
def reducer_sum(s, cur):
   return s + cur

The reduce() function in Python allows you to do one-liner without need to write a loop.

How is reduce() implemented in Python?

The reduce() function is as simple as the following:

1
2
3
4
5
def reduce(reducer, data, value):
   cur = value
   for i in data:
      cur = reducer(cur, i)
   return cur
def reduce(reducer, data, value):
   cur = value
   for i in data:
      cur = reducer(cur, i)
   return cur

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
对于新站来说:如何让网站快速被搜索引擎收录呢?  网站内部优化细节流程(纯白帽SEO)  网站安全防止被黑客攻击的办法  我在落伍的那几年:一个个人站长的回忆录  给哪些网站暂时赚不到钱的站长鼓鼓劲  个人站长 建设网站贵在坚持  网站站长赚钱的6大好用的途径  整理6款站长赚钱方法 希望对你有所帮助  个人站长们常见的很多个网站盈利模式总结  春季饮食宜润肺,常吃炖梨既滋润又养人,口感甜香味道美 
评论列表
添加评论