当前位置:网站首页>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

边栏推荐
- Keepalived set the master not to recapture the VIP after fault recovery (it is invalid to solve nopreempt)
- Management and thesis of job management system based on SSM
- WordPress collection WordPress hang up collection plug-in
- 7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
- Contest3145 - the 37th game of 2021 freshman individual training match_ E: Eat watermelon
- Day05 錶格
- Nbear introduction and use diagram
- [database I] database overview, common commands, view the table structure of 'demo data', simple query, condition query, sorting data, data processing function (single row processing function), groupi
- [Valentine's Day confession code] - Valentine's Day is approaching, and more than 10 romantic love effects are given to the one you love
- Unity knapsack system (code to center and exchange items)
猜你喜欢

WordPress collection WordPress hang up collection plug-in

Practical multifunctional toolbox wechat applet source code / support traffic master

Jenkins configures IP address access

Pagoda SSL can't be accessed? 443 port occupied? resolvent

MySQL query
![[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush](/img/94/2bdc31ec05595dbbc8a7a8d6b22252.jpg)
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush

Jenkins continuous integration environment construction V (Jenkins common construction triggers)

Rhcsa day 3

Add token validation in swagger

The difference between MCU serial communication and parallel communication and the understanding of UART
随机推荐
No clue about the data analysis report? After reading this introduction of smartbi, you will understand!
[development team follows] API specification
PMP 考試常見工具與技術點總結
機器學習基礎:用 Lasso 做特征選擇
Redis notes (I) Linux installation process of redis
Leetcode51.n queen
Setting methods, usage methods and common usage scenarios of environment variables in postman
Li Chuang EDA learning notes IX: layers
MySQL query
1day vulnerability pushback skills practice (3)
Package and download 10 sets of Apple CMS templates / download the source code of Apple CMS video and film website
[UE4] parse JSON string
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
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
PID of sunflower classic
Practical multifunctional toolbox wechat applet source code / support traffic master
[Valentine's Day confession code] - Valentine's Day is approaching, and more than 10 romantic love effects are given to the one you love
What kind of experience is it when the Institute earns 20000 yuan a month!
Contest3145 - the 37th game of 2021 freshman individual training match_ J: Eat radish
Redis transaction