当前位置:网站首页>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
边栏推荐
- Defensive programming skills
- Session learning diary 1
- Which product is better for 2022 annual gold insurance?
- Detailed explanation of PPTC self recovery fuse
- Webhook triggers Jenkins for sonar detection
- Jenkins configures IP address access
- The difference between MCU serial communication and parallel communication and the understanding of UART
- XSS prevention
- PHP database connection succeeded, but data cannot be inserted
- Explain AI accelerator in detail: why is this the golden age of AI accelerator?
猜你喜欢
Katalon框架测试web(二十六)自动发邮件
Setting methods, usage methods and common usage scenarios of environment variables in postman
Stm32bug [stlink forced update prompt appears in keilmdk, but it cannot be updated]
选择排序与冒泡排序模板
Consul of distributed service registration discovery and unified configuration management
Want to do something in production? Then try these redis commands
Explain AI accelerator in detail: why is this the golden age of AI accelerator?
Infiltration practice guest account mimikatz sunflower SQL rights lifting offline decryption
Audio and video technology development weekly | 232
[Valentine's Day confession code] - Valentine's Day is approaching, and more than 10 romantic love effects are given to the one you love
随机推荐
【.NET+MQTT】.NET6 環境下實現MQTT通信,以及服務端、客戶端的雙邊消息訂閱與發布的代碼演示
Contest3145 - the 37th game of 2021 freshman individual training match_ G: Score
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
The property of judging odd or even numbers about XOR.
Cache general management class + cache httpcontext Current. Cache and httpruntime Differences between caches
Objective-C description method and type method
[PaddleSeg 源码阅读] PaddleSeg Transform 的 Normalize操作
How much does it cost to open a futures account in China? Where is it safe to open an account at present?
Day05 錶格
Package and download 10 sets of Apple CMS templates / download the source code of Apple CMS video and film website
Exercices de renforcement des déclarations SQL (MySQL 8.0 par exemple)
Is it really so difficult to learn redis? Today, a fan will share his personal learning materials!
GUI Graphical user interface programming (XIV) optionmenu - what do you want your girlfriend to wear on Valentine's day
JVM family -- heap analysis
Eh, the log time of MySQL server is less than 8h?
SQL injection (1) -- determine whether there are SQL injection vulnerabilities
2022 Guangxi provincial safety officer a certificate examination materials and Guangxi provincial safety officer a certificate simulation test questions
Leecode 122. Zuijia timing of buying and selling stocks ②
Contest3145 - the 37th game of 2021 freshman individual training match_ J: Eat radish
PID of sunflower classic