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

边栏推荐
- JVM family -- heap analysis
- Why is it recommended that technologists write blogs?
- Infiltration practice guest account mimikatz sunflower SQL rights lifting offline decryption
- Tsinghua University product: penalty gradient norm improves generalization of deep learning model
- MySQL one master multiple slaves + linear replication
- Command Execution Vulnerability - command execution - vulnerability sites - code injection - vulnerability exploitation - joint execution - bypass (spaces, keyword filtering, variable bypass) - two ex
- 基于PHP的轻量企业销售管理系统
- MySQL data query optimization -- data structure of index
- Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]
- Zigzag scan
猜你喜欢

Setting methods, usage methods and common usage scenarios of environment variables in postman

Contest3145 - the 37th game of 2021 freshman individual training match_ 1: Origami

(column 23) typical C language problem: find the minimum common multiple and maximum common divisor of two numbers. (two solutions)

Package details_ Four access control characters_ Two details of protected

This function has none of DETERMINISTIC, NO SQL..... (you *might* want to use the less safe log_bin_t

SQL语句加强练习(MySQL8.0为例)

What is cloud primordial?

Why is it recommended that technologists write blogs?

EV6 helps the product matrix, and Kia is making efforts in the high-end market. The global sales target in 2022 is 3.15 million?

How to use websocket to realize simple chat function in C #
随机推荐
How to pipe several commands in Go?
[PaddleSeg 源码阅读] PaddleSeg 自定义数据类
Mindmanager2022 efficient and easy to use office mind map MindManager
Package and download 10 sets of Apple CMS templates / download the source code of Apple CMS video and film website
PMP 考試常見工具與技術點總結
Code Execution Vulnerability - no alphanumeric rce create_ function()
Future源碼一觀-JUC系列
Exercices de renforcement des déclarations SQL (MySQL 8.0 par exemple)
PHP database connection succeeded, but data cannot be inserted
CSP drawing
2022-07-03:数组里有0和1,一定要翻转一个区间,翻转:0变1,1变0。 请问翻转后可以使得1的个数最多是多少? 来自小红书。3.13笔试。
Easy to win insert sort
[development team follows] API specification
JVM family -- monitoring tools
投资深度思考
MySQL maxscale realizes read-write separation
[PaddleSeg 源码阅读] PaddleSeg计算Dice
SQL injection (1) -- determine whether there are SQL injection vulnerabilities
The 37 year old programmer was laid off, and he didn't find a job for 120 days. He had no choice but to go to a small company. As a result, he was confused
[Valentine's Day confession code] - Valentine's Day is approaching, and more than 10 romantic love effects are given to the one you love