问题描述
我有这个:
>>> sum( i*i for i in xrange(5))
我的问题是,在这种情况下,我是否将列表理解或生成器对象传递给以求和?我该怎么讲?对此有一般规则吗?
My question is, in this case am I passing a list comprehension or a generator object to sum ? How do I tell that? Is there a general rule around this?
还请记住,总和本身需要一对括号来包围其参数.我认为上面的括号是求和而不是用于创建生成器对象.您不同意吗?
Also remember sum by itself needs a pair of parentheses to surround its arguments. I'd think that the parentheses above are for sum and not for creating a generator object. Wouldn't you agree?
推荐答案
您正在传递生成器表达式.
列表理解用方括号指定([...]
).列表理解首先会构建一个 list对象,因此它使用与列表文字语法密切相关的语法:
A list comprehension is specified with square brackets ([...]
). A list comprehension builds a list object first, so it uses syntax closely related to the list literal syntax:
list_literal = [1, 2, 3]
list_comprehension = [i for i in range(4) if i > 0]
另一方面,生成器表达式创建一个迭代器对象.只有在对该对象进行遍历时,才会执行包含的循环并生成项目.生成器表达式不会保留这些项目;没有构建列表对象.
A generator expression, on the other hand, creates an iterator object. Only when iterating over that object is the contained loop executed and are items produced. The generator expression does not retain those items; there is no list object being built.
生成器表达式始终使用(...)
圆括号,但是当用作仅 调用的参数时,可以省略括号.以下两个表达式是等效的:
A generator expression always uses (...)
round parethesis, but when used as the only argument to a call, the parenthesis can be omitted; the following two expressions are equivalent:
sum((i*i for i in xrange(5))) # with parenthesis
sum(i*i for i in xrange(5)) # without parenthesis around the generator
从生成器表达式文档中引用:
Quoting from the generator expression documentation:
这篇关于如何识别生成器vs列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!