The Reduce Function in Python
- 时间:2020-09-13 14:33:25
- 分类:网络文摘
- 阅读:154 次
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) —
推荐阅读:功能性饮料应该如何科学合理的饮用 网传的10种致癌食物中有9种不靠谱 夏季常见水果:西瓜的营养保健价值 健康食品黑枣的食疗功效与营养价值 保健食品当做药品卖“脑力风暴”骗局 “公益网站”牵线 保健食品当药品卖 消费者如何正确选择购买保健食品 中国拟新制定五项食品安全国家标准 脑力劳动者如何科学补充食物营养? 食品中的肉毒杆菌对儿童的危害很大
- 评论列表
-
- 添加评论