Python:下一个()函数

Python: next() function(Python:下一个()函数)
本文介绍了Python:下一个()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在从一本书中学习 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) 创建了所谓的 generator.此生成器将为 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

另见:

  • 关于生成器的文档
  • 关于 yield 表达式的文档(包含一些关于生成器的信息)
  • See also:

    • Documentation on generators
    • Documentation on yield expressions (with some info about generators)
    • 这篇关于Python:下一个()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

      本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)