当前位置:网站首页>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
边栏推荐
- Explain AI accelerator in detail: why is this the golden age of AI accelerator?
- Eh, the log time of MySQL server is less than 8h?
- Nbear introduction and use diagram
- Constantly changing harmonyos custom JS components during the Spring Festival - Smart Koi
- Slurm view node configuration information
- Backpropagation formula derivation [Li Hongyi deep learning version]
- Third party login initial version
- Command Execution Vulnerability - command execution - vulnerability sites - code injection - vulnerability exploitation - joint execution - bypass (spaces, keyword filtering, variable bypass) - two ex
- Consul of distributed service registration discovery and unified configuration management
- 基於.NetCore開發博客項目 StarBlog - (14) 實現主題切換功能
猜你喜欢
Summary of Chinese remainder theorem
MySQL query
Third party login initial version
PID of sunflower classic
What kind of experience is it when the Institute earns 20000 yuan a month!
Dare to climb here, you're not far from prison, reptile reverse actual combat case
1day vulnerability pushback skills practice (3)
Leetcode51.n queen
What is the difference between enterprise wechat applet and wechat applet
Li Chuang EDA learning notes 13: electrical network for drawing schematic diagram
随机推荐
How about the ratings of 2022 Spring Festival Gala in all provinces? Map analysis helps you show clearly!
查詢效率提昇10倍!3種優化方案,幫你解决MySQL深分頁問題
Safety tips - seat belt suddenly fails to pull? High speed police remind you how to use safety belts in a standardized way
super_ Subclass object memory structure_ Inheritance tree traceability
96% of the collected traffic is prevented by bubble mart of cloud hosting
Session learning diary 1
Setting methods, usage methods and common usage scenarios of environment variables in postman
Package details_ Four access control characters_ Two details of protected
Recursive structure
Monitoring - Prometheus introduction
Examination question bank of constructor decoration direction post skills (constructor) and examination data of constructor decoration direction post skills (constructor) in 2022
[UE4] parse JSON string
Development of digital collection trading platform development of digital collection platform
MySQL data query optimization -- data structure of index
[untitled]
Future源碼一觀-JUC系列
The difference between MCU serial communication and parallel communication and the understanding of UART
Audio and video technology development weekly | 232
System integration meets the three business needs of enterprises
Li Chuang EDA learning notes IX: layers