sum函数如何在带有for循环的python中工作 [英] How does sum function work in python with for loop

查看:303
本文介绍了sum函数如何在带有for循环的python中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在pyhton中使用sum函数,并且很清楚它的一般结构 sum(iterable,start),但是我无法理解下面代码的逻辑

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

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

输出:25

请任何人描述这里发生的事情,基本上这里是5与5的乘积,并且每个样本输入都具有相同的模式.

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.

推荐答案

您的代码是以下代码的简写:

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.

(5 for i in range(5))组件是生成器表达式,每次迭代都会产生值5.根据range(5)的定义,生成器表达式总共有5次迭代.因此,生成器表达式的准确率是5的5倍.

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). Therefore, the generator expression yields 5 exactly 5 times.

sum 接受任何 iterable ,甚至那些 not 都完全保留在内存中.生成器(通过扩展生成器表达式)可以提高内存效率.因此,您的逻辑将精确地相加5次5次,即25次.

sum, as the docs indicate, accepts any iterable, even those not held entirely in memory. Generators, and by extension generator expressions, are memory efficient. Therefore, your logic will sum 5 exactly 5 times, which equals 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))

这篇关于sum函数如何在带有for循环的python中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆