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

边栏推荐
- The property of judging odd or even numbers about XOR.
- Contest3145 - the 37th game of 2021 freshman individual training match_ G: Score
- 7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
- false sharing
- Baijia forum the founding of the Eastern Han Dynasty
- Is it really so difficult to learn redis? Today, a fan will share his personal learning materials!
- How about the ratings of 2022 Spring Festival Gala in all provinces? Map analysis helps you show clearly!
- 機器學習基礎:用 Lasso 做特征選擇
- WordPress collection WordPress hang up collection plug-in
- PHP database connection succeeded, but data cannot be inserted
猜你喜欢

Setting methods, usage methods and common usage scenarios of environment variables in postman

Johnson–Lindenstrauss Lemma

1day vulnerability pushback skills practice (3)
![[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
![Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]](/img/0d/7a8370d153a8479b706377c3487220.jpg)
Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]

MySQL query

Webhook triggers Jenkins for sonar detection

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

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

Unspeakable Prometheus monitoring practice
随机推荐
How much does it cost to open a futures account in China? Where is it safe to open an account at present?
logistic regression
GUI Graphical user interface programming (XIV) optionmenu - what do you want your girlfriend to wear on Valentine's day
Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
Contest3145 - the 37th game of 2021 freshman individual training match_ G: Score
Talking about custom conditions and handling errors in MySQL Foundation
Baijia forum the founding of the Eastern Han Dynasty
Remote work guide
7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
Lichuang EDA learning notes 14: PCB board canvas settings
機器學習基礎:用 Lasso 做特征選擇
Imperial cms7.5 imitation "D9 download station" software application download website source code
Session learning diary 1
Add token validation in swagger
In my spare time, I like to write some technical blogs and read some useless books. If you want to read more of my original articles, you can follow my personal wechat official account up technology c
Redis notes (I) Linux installation process of redis
PHP database connection succeeded, but data cannot be inserted
Setting methods, usage methods and common usage scenarios of environment variables in postman
Leetcode51.n queen
SQL injection (1) -- determine whether there are SQL injection vulnerabilities