Let's look at an example which summarizes some details, yielding
the summaries. Assume we have the following list
of tuples. We want to know how many red spins
separate a black spin, on average. We need a function which will yield
the count of gaps as it examines the spins. We can then call this
function repeatedly to get the gap information.
Example 18.1. generator.py
spins = [('red', '18'), ('black', '13'), ('red', '7'),
('red', '5'), ('black', '13'), ('red', '25'),
('red', '9'), ('black', '26'), ('black', '15'),
('black', '20'), ('black', '31'), ('red', '3')]
def countReds( aList ):
count= 0
for color,number in aList:
if color == 'black':
yield count
count= 0
else:
count += 1
yield count
gaps= [ gap for gap in countReds(spins) ]
print gaps
The spin variable defines our sample
data. This might be an actual record of spins.
We define our
gapCount(aList )
function. This function initializes count to
show the number of non-black's before a black. It then steps
through the individual spins, in the order presented. For
non-black's, the count is incremented.
For black spins, however, we yield the length of the gap
between the last black. When we yield a result, the generator
produces a result value, and also saves all the other processing
information about this function so that it can be continued from
this point.
When the function is continued, it resumes right after the
yield statement: the count will be reset, and
the for loop will advance to examine the next
number in the sequence.
When the sequence is exhausted, we also yield the final
count. The first and last gap counts may have to be discarded
for certain kinds of statistical analysis.
This shows how we use the generator created by a function
with a yield statement. In this case, we
create a list comprehension; the
for clause will step through the values
yielded by the generator until the it exits normally. This
sequence of values is collected into a
list that we can the use for statistical
analysis.
Published under the terms of the Open Publication License