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

边栏推荐
- I stepped on a foundation pit today
- 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
- [untitled]
- Eh, the log time of MySQL server is less than 8h?
- Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
- Monitoring - Prometheus introduction
- What is cloud primordial?
- Contest3145 - the 37th game of 2021 freshman individual training match_ D: Ranking
- Unity controls the selection of the previous and next characters
- Which product is better for 2022 annual gold insurance?
猜你喜欢

National standard gb28181 protocol platform easygbs fails to start after replacing MySQL database. How to deal with it?
![Backpropagation formula derivation [Li Hongyi deep learning version]](/img/ef/f76eae39c4f8716a0030a60c85b09c.gif)
Backpropagation formula derivation [Li Hongyi deep learning version]

Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics

Unspeakable Prometheus monitoring practice

Monitoring - Prometheus introduction

Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?

Zhihu million hot discussion: why can we only rely on job hopping for salary increase? Bosses would rather hire outsiders with a high salary than get a raise?

Audio and video technology development weekly | 232

Talking about custom conditions and handling errors in MySQL Foundation

How about the ratings of 2022 Spring Festival Gala in all provinces? Map analysis helps you show clearly!
随机推荐
Enhanced for loop
Why is it recommended that technologists write blogs?
7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
WP collection plug-in free WordPress collection hang up plug-in
Résumé: entropie, énergie libre, symétrie et dynamique dans le cerveau
CSCI 2134
Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
Redis notes (I) Linux installation process of redis
Which product is better if you want to go abroad to insure Xinguan?
Monitoring - Prometheus introduction
Management and thesis of job management system based on SSM
Résumé des outils communs et des points techniques de l'examen PMP
I stepped on a foundation pit today
Experience summary of the 12th Blue Bridge Cup (written for the first time)
Love and self-discipline and strive to live a core life
Examination question bank of constructor decoration direction post skills (constructor) and examination data of constructor decoration direction post skills (constructor) in 2022
Contest3145 - the 37th game of 2021 freshman individual training match_ D: Ranking
No clue about the data analysis report? After reading this introduction of smartbi, you will understand!
Cache general management class + cache httpcontext Current. Cache and httpruntime Differences between caches
Session learning diary 1