Python `for` 语法:块代码与单行生成器表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12920214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python `for` syntax: block code vs single line generator expressions
提问by ivan
I'm familiar with the forloop in a block-code context. eg:
我熟悉for块代码上下文中的循环。例如:
for c in "word":
print c
I just came across some examples that use fordifferently. Rather than beginning with the forstatement, they tag it at the end of an expression (and don't involve an indented code-block). eg:
我刚刚遇到了一些使用方式for不同的例子。他们不是从for语句开始,而是在表达式的末尾标记它(并且不涉及缩进的代码块)。例如:
sum(x*x for x in range(10))
Can anyone point me to some documentation that outlines this use of for? I've been able to find examples, but not explanations. All the fordocumentation I've been able to find describes the previous use (block-code example). I'm not even sure what to call this use, so I apologize if my question's title is unclear.
任何人都可以向我指出一些概述这种用法的文档for吗?我已经能够找到例子,但没有解释。for我能找到的所有文档都描述了以前的使用(块代码示例)。我什至不确定如何称呼这种用途,所以如果我的问题标题不清楚,我深表歉意。
采纳答案by Rohit Jain
What you are pointing to is Generatorin Python. Take a look at: -
您所指的是Generator在 Python 中。看一眼: -
- http://wiki.python.org/moin/Generators
- http://www.python.org/dev/peps/pep-0255/
- http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features
- http://wiki.python.org/moin/Generators
- http://www.python.org/dev/peps/pep-0255/
- http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features
See the documentation: - Generator Expressionwhich contains exactly the same example you have posted
请参阅文档:-Generator Expression其中包含与您发布的示例完全相同的示例
From the documentation: -
从文档: -
Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called, the generator resumes where it left-off (it remembers all the data values and which statement was last executed)
生成器是用于创建迭代器的简单而强大的工具。它们的编写方式与常规函数类似,但在需要返回数据时使用 yield 语句。每次 next() 被调用时,生成器从它离开的地方恢复(它记住所有数据值和最后执行的语句)
Generators are similar to List Comprehensionthat you use with square bracketsinstead of brackets, but they are more memory efficient. They don't return the complete listof result at the same time, but they return generator object. Whenever you invoke next()on the generatorobject, the generator uses yieldto return the next value.
生成器类似于List Comprehension您使用 withsquare brackets而不是 的生成器brackets,但它们的内存效率更高。它们不会同时返回完整list的结果,而是返回生成器对象。每次调用next()上的generator对象,生成器使用yield返回下一个值。
List Comprehensionfor the above code would look like: -
List Comprehension上面的代码看起来像: -
[x * x for x in range(10)]
You can also add conditions to filter out results at the end of the for.
您还可以添加条件以过滤掉 for 末尾的结果。
[x * x for x in range(10) if x % 2 != 0]
This will return a list of numbersmultiplied by 2 in the range 1 to 5, if the number is not divisible by 2.
numbers如果数字不能被 2 整除,这将返回一个1 到 5 范围内的乘以 2的列表。
An example of Generatorsdepicting the use of yieldcan be: -
Generators描述使用的一个例子yield可以是: -
def city_generator():
yield("Konstanz")
yield("Zurich")
yield("Schaffhausen")
yield("Stuttgart")
>>> x = city_generator()
>>> x.next()
Konstanz
>>> x.next()
Zurich
>>> x.next()
Schaffhausen
>>> x.next()
Stuttgart
>>> x.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
So, you see that, every call to next()executes the next yield()in generator. and at the end it throws StopIteration.
所以,你看到的是,每一个呼叫next()下一个执行yield()在generator。最后它抛出StopIteration.
回答by Rohit Jain
Your specific example is called a generator expression. List comprehensions, dictionary comprehensions, and set comprehensionsare similar in meaning (different result types, and generator expressions are lazy) and have the same syntax, modulo being inside other kinds of brackets, and in the case of a dict comprehension having expr1: expr2instead of a single expression (x*x in your example).
您的具体示例称为生成器表达式。列表推导式、字典推导式和集合推导式的含义相似(不同的结果类型,并且生成器表达式是惰性的)并且具有相同的语法,模数位于其他类型的括号内,并且在字典推导式的情况下具有expr1: expr2而不是单个表达式(在您的示例中为 x*x)。
回答by Matt
Those are generator expressionsand they are related to list comprehensions
List comprehensions allow for the easy creation of lists. For example, if you wanted to create a list of perfect squares you could do this:
列表推导式允许轻松创建列表。例如,如果您想创建一个完美正方形列表,您可以这样做:
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
But instead you could use a list comprehension:
但是,您可以使用列表理解:
squares = [x**2 for x in range(10)]
Generator expressions are like list comprehensions, except they return a generator object instead of a list. You can iterate over this generator object in a similar manner to list comprehensions, but you don't have to store the whole list in memory at once, as you would if you created the list in a list comprehension.
生成器表达式类似于列表推导式,除了它们返回生成器对象而不是列表。您可以以类似于列表推导式的方式迭代此生成器对象,但您不必像在列表推导式中创建列表那样一次性将整个列表存储在内存中。
回答by Saurabh
Documentation for generator expressions is here https://www.python.org/dev/peps/pep-0289/Following is the code using generator expression .
生成器表达式的文档在这里https://www.python.org/dev/peps/pep-0289/以下是使用生成器表达式的代码。
list(x**2 for x in range(0,10))

