Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

sum - Python: next() function

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...