我正在从一本书中学习 Python,我遇到了这个例子:
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() 函数提供任何解释,所以我不明白代码在做什么。
最佳答案
表达式(sum(row) for row in M)
创建了所谓的generator。此生成器将为 M
中的每一行计算一次表达式 (sum(row)
)。但是,生成器还没有做任何事情,我们只是设置好了。
语句next(G)
实际上运行 M
上的生成器。因此,如果您运行一次 next(G)
,您将获得第一行的总和。如果你再次运行它,你会得到第二行的总和,以此类推。
>>> 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 (包含一些关于生成器的信息)
关于Python:下一个()函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1733004/