当前位置:网站首页>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)
- 2022 examination summary of quality controller - Equipment direction - general basis (quality controller) and examination questions and analysis of quality controller - Equipment direction - general b
- 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
- MySQL query
- Development of digital collection trading platform development of digital collection platform
- What is cloud primordial?
- Defensive programming skills
- Contest3145 - the 37th game of 2021 freshman individual training match_ E: Eat watermelon
- Aperçu du code source futur - série juc
- Leecode 122. Zuijia timing of buying and selling stocks ②
猜你喜欢

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

Unity knapsack system (code to center and exchange items)
![[Valentine's Day confession code] - Valentine's Day is approaching, and more than 10 romantic love effects are given to the one you love](/img/ab/066923f1aa1e8dd8dcc572cb60a25d.jpg)
[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 is cloud primordial?

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

Tsinghua University product: penalty gradient norm improves generalization of deep learning model

長文綜述:大腦中的熵、自由能、對稱性和動力學

1day vulnerability pushback skills practice (3)

Don't disagree, this is the most powerful "language" of the Internet

Hospital network planning and design document based on GLBP protocol + application form + task statement + opening report + interim examination + literature review + PPT + weekly progress + network to
随机推荐
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
Dare to climb here, you're not far from prison, reptile reverse actual combat case
Li Chuang EDA learning notes IX: layers
How much does it cost to open a futures account in China? Where is it safe to open an account at present?
Consul of distributed service registration discovery and unified configuration management
Learning video website
Constantly changing harmonyos custom JS components during the Spring Festival - Smart Koi
How about the ratings of 2022 Spring Festival Gala in all provinces? Map analysis helps you show clearly!
[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
false sharing
7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
基於.NetCore開發博客項目 StarBlog - (14) 實現主題切換功能
Contest3145 - the 37th game of 2021 freshman individual training match_ G: Score
PID of sunflower classic
System integration meets the three business needs of enterprises
Monitoring - Prometheus introduction
New year's first race, submit bug reward more!
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"
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?
Contest3145 - the 37th game of 2021 freshman individual training match_ F: Smallest ball