简体   繁体   English

sum函数如何在python中使用for循环

[英]How does sum function work in python with for loop

I was using sum function in pyhton, and i am clear about it's general structure sum(iterable, start) , but i am unable to get the logic behind the following code 我在pyhton中使用sum函数,我很清楚它的一般结构总和(可迭代,开始) ,但我无法得到以下代码背后的逻辑

test = sum(5 for i in range(5) )
print("output:  ", test) 

output: 25 输出:25

Please can anyone describe what is happening here, basically here 5 is getting multiplied with 5, and same pattern is there for every sample input. 请任何人都能描述这里发生的事情,基本上这里5乘以5,每个样本输入都有相同的模式。

Your code is shorthand for: 您的代码是:

test = sum((5 for i in range(5)))

The removal of extra parentheses is syntactic sugar: it has no impact on your algorithm. 删除额外的括号是语法糖:它对您的算法没有影响。

The (5 for i in range(5)) component is a generator expression which, on each iteration, yields the value 5. Your generator expression has 5 iterations in total, as defined by range(5) . (5 for i in range(5))组件是一个生成器表达式 ,在每次迭代时产生值5.您的生成器表达式总共有5次迭代,由range(5)定义。 Therefore, the generator expression yields 5 exactly 5 times. 因此,生成器表达式恰好产生5次5次。

sum , as the docs indicate, accepts any iterable , even those not held entirely in memory. sum ,正如文档所指出的那样,接受任何可迭代的 ,甚至是那些完全不在记忆中的迭代 Generators, and by extension generator expressions, are memory efficient. 生成器和扩展生成器表达式具有内存效率。 Therefore, your logic will sum 5 exactly 5 times, which equals 25. 因此,你的逻辑将恰好相加5次5次,相当于25次。

A convention when you don't use a variable in a closed loop is to denote that variable by underscore ( _ ), so usually you'll see your code written as: 在闭环中不使用变量时的约定是用下划线( _ )表示该变量,所以通常你会看到你的代码写成:

test = sum(5 for _ in range(5))

You can add a list to the sum function so you can make something like this: 您可以向sum函数添加一个列表,这样您就可以这样做:

test = sum((1,23,5,6,100))
print("output:  ", test) 

And you get 135 . 你得到135

So with your "for loop" you get a list and put that list to the sum function and you get the sum of the list. 因此,使用“for循环”,您将获得一个列表并将该列表放入sum函数,并获得列表的总和。 The real sum function uses yield insight and use every value and sum them up. 真实的sum函数使用yield insight并使用每个值并总结它们。

Basically, it is summing 5 repeativily for every "i" on range(5). 基本上,它是对范围(5)上的每个“i”重复求和5。 Meaning, this code is equivalent to n*5, being n the size of range(n). 意思是,这段代码相当于n * 5,n是范围(n)的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM