当前位置:网站首页>Reduce function under functools
Reduce function under functools
2022-07-04 03:37:00 【Master Fuwen】
Take a look reduce Source code :
################################################################################
### 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) # <----------- Turn it into an iterator
if initial is _initial_missing:
try:
value = next(it) # <----------- obtain it The first element of
except StopIteration:
raise TypeError("reduce() of empty sequence with no initial value") from None
else:
value = initial # <----------- This step is generally useless , Unless you manually specify the initial element
for element in it:
value = function(value, element) # If value = next(it) Then start with the second element
# If value = initial be for from it The first element of begins
return value
Look at the notes above , It's even clearer :
From left to right , Divide the sequence elements into pairs , Until it is an element
for instance :reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
Finally, this result is returned :
((((1+2)+3)+4)+5)
If
initial
Pass in the parameter , Then it will be placed before the items of the sequence in the calculation , And used as the default value when the sequence is empty
Let's take another example :
stay PaddleSeg Transform Normalize Of __init__
in , There are three lines :
from functools import reduce
if reduce(lambda x, y: x * y, self.std) == 0:
raise ValueError('{}: std is invalid!'.format(self))
It's really just the self.std Multiply the three elements of , If one element is 0, be raise ValueError
( because self.std Be the denominator )
But it's actually from _functools The , I didn't use the above Python Code
try:
from _functools import reduce
except ImportError:
pass
边栏推荐
- MySQL one master multiple slaves + linear replication
- 2022 Guangxi provincial safety officer a certificate examination materials and Guangxi provincial safety officer a certificate simulation test questions
- Slurm view node configuration information
- Defensive programming skills
- [source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
- Contest3145 - the 37th game of 2021 freshman individual training match_ F: Smallest ball
- Add token validation in swagger
- The difference between MCU serial communication and parallel communication and the understanding of UART
- Apple submitted the new MAC model to the regulatory database before the spring conference
- [PaddleSeg 源码阅读] PaddleSeg计算Dice
猜你喜欢
PHP database connection succeeded, but data cannot be inserted
Session learning diary 1
How to use websocket to realize simple chat function in C #
Development of digital collection trading platform development of digital collection platform
渗透实战-guest账户-mimikatz-向日葵-sql提权-离线解密
Objective-C description method and type method
What are the virtual machine software? What are their respective functions?
The difference between MCU serial communication and parallel communication and the understanding of UART
[Valentine's Day confession code] - Valentine's Day is approaching, and more than 10 romantic love effects are given to the one you love
Third party login initial version
随机推荐
[.NET + mqtt]. Mise en œuvre de la communication mqtt dans l'environnement net 6 et démonstration de code pour l'abonnement et la publication de messages bilatéraux du serveur et du client
1day vulnerability pushback skills practice (3)
Contest3145 - the 37th game of 2021 freshman individual training match_ G: Score
Leetcode51.n queen
JVM family -- monitoring tools
How much does it cost to open a futures account in China? Where is it safe to open an account at present?
How to pipe several commands in Go?
The difference between MCU serial communication and parallel communication and the understanding of UART
2022 Guangxi provincial safety officer a certificate examination materials and Guangxi provincial safety officer a certificate simulation test questions
Basé sur... Netcore Development blog Project Starblog - (14) Implementation of theme switching function
Objective-C string class, array class
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
Contest3145 - the 37th game of 2021 freshman individual training match_ 1: Origami
Recent learning fragmentation (14)
Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]
选择排序与冒泡排序模板
Which product is better if you want to go abroad to insure Xinguan?
Calculate the odd sum of 1~n (1~100 as an example)
AAAI2022 | Word Embeddings via Causal Inference: Gender Bias Reducing and Semantic Information Preserving
Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics