Python:next()函数 [英] Python: next() function
问题描述
我正在从一本书中学习Python,并且遇到了以下示例:
I'm learning Python from a book, and I came across this example:
M = [[1,2,3],
[4,5,6],
[7,8,9]]
G = (sum(row) for row in M) # create a generator of row sums
next(G) # Run the iteration protocol
由于我是一个绝对的初学者,并且作者没有提供有关示例或next()函数的任何解释,所以我不理解代码在做什么.
Since I'm an absolute beginner, and the author hasn't provided any explanation of the example or the next() function, I don't understand what the code is doing.
推荐答案
表达式(sum(row) for row in M)
创建所谓的生成器.该生成器将对M
中的每一行一次计算表达式(sum(row)
).但是,生成器尚未执行任何操作,我们已经对其进行了设置.
The expression (sum(row) for row in M)
creates what's called a generator. This generator will evaluate the expression (sum(row)
) once for each row in M
. However, the generator doesn't do anything yet, we've just set it up.
语句next(G)
实际上在M
上运行 生成器.因此,如果您运行一次next(G)
,您将获得第一行的总和.如果再次运行它,将得到第二行的总和,依此类推.
The statement next(G)
actually runs the generator on M
. So, if you run next(G)
once, you'll get the sum of the first row. If you run it again, you'll get the sum of the second row, and so on.
>>> M = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>>
>>> G = (sum(row) for row in M) # create a generator of row sums
>>> next(G) # Run the iteration protocol
6
>>> next(G)
15
>>> next(G)
24
另请参见:
- 关于生成器的文档
- 关于收益表达式的文档(以及有关生成器的一些信息)
- Documentation on generators
- Documentation on yield expressions (with some info about generators)
See also:
这篇关于Python:next()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!