当前位置:网站首页>functools下的reduce函数
functools下的reduce函数
2022-07-04 03:32:00 【氵文大师】
来看下 reduce 的源码:
################################################################################
### reduce() sequence to a single item
################################################################################
_initial_missing = object()
def reduce(function, sequence, initial=_initial_missing):
""" 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. """
it = iter(sequence) # <----------- 将其变为一个迭代器
if initial is _initial_missing:
try:
value = next(it) # <----------- 取得 it 的第一个元素
except StopIteration:
raise TypeError("reduce() of empty sequence with no initial value") from None
else:
value = initial # <----------- 这一步一般没啥用,除非你手动指定最初元素
for element in it:
value = function(value, element) # 如果 value = next(it) 则从第二个元素开始
# 如果 value = initial 则 for 从 it 的第一个元素开始
return value
看下上边的注释,就更清楚了:
从左到右,将序列元素两两规约,直到为一个元素
举个例子:reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])最后返回的是这个结果:
((((1+2)+3)+4)+5)如果
initial传入参数,则在计算中将其放置在序列的项目之前,并在序列为空时用作默认值
再来看个例子:
在PaddleSeg Transform Normalize 的 __init__ 中,有这么三行:
from functools import reduce
if reduce(lambda x, y: x * y, self.std) == 0:
raise ValueError('{}: std is invalid!'.format(self))
其实就是将 self.std 的三个元素相乘,如果有一个元素为0,则 raise ValueError
(因为 self.std 要做分母)
然而实际上是 从 _functools 中导入的,并没有用上边的Python代码
try:
from _functools import reduce
except ImportError:
pass

边栏推荐
- Contest3145 - the 37th game of 2021 freshman individual training match_ E: Eat watermelon
- Add token validation in swagger
- Recursive structure
- I stepped on a foundation pit today
- How to pipe several commands in Go?
- 2022 Guangxi provincial safety officer a certificate examination materials and Guangxi provincial safety officer a certificate simulation test questions
- What are the virtual machine software? What are their respective functions?
- @Scheduled scheduled tasks
- Monitoring - Prometheus introduction
- Contest3145 - the 37th game of 2021 freshman individual training match_ G: Score
猜你喜欢

GUI Graphical user interface programming (XIV) optionmenu - what do you want your girlfriend to wear on Valentine's day

WP collection plug-in free WordPress collection hang up plug-in

MySQL is dirty

Zblog collection plug-in does not need authorization to stay away from the cracked version of zblog

7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages

The first spring of the new year | a full set of property management application templates are presented, and Bi construction is "out of the box"

This function has none of DETERMINISTIC, NO SQL..... (you *might* want to use the less safe log_bin_t

Rhcsa day 3

A brief talk on professional modeler: the prospect and professional development of 3D game modeling industry in China

MySQL query
随机推荐
logistic regression
Love and self-discipline and strive to live a core life
Problems and solutions of several concurrent scenarios of redis
Constantly changing harmonyos custom JS components during the Spring Festival - Smart Koi
[Valentine's Day confession code] - Valentine's Day is approaching, and more than 10 romantic love effects are given to the one you love
I stepped on a foundation pit today
Li Chuang EDA learning notes IX: layers
Formulaire day05
[development team follows] API specification
Amélioration de l'efficacité de la requête 10 fois! 3 solutions d'optimisation pour résoudre le problème de pagination profonde MySQL
Management and thesis of job management system based on SSM
The first spring of the new year | a full set of property management application templates are presented, and Bi construction is "out of the box"
JS object definition
Redis transaction
How to pipe several commands in Go?
Recent learning fragmentation (14)
How to use websocket to realize simple chat function in C #
Unity knapsack system (code to center and exchange items)
What are the conditions for the opening of Tiktok live broadcast preview?
Optimization theory: definition of convex function + generalized convex function