I need a 2D loop of which the first loop uses an iterator and the second uses a generator, but this simple function failed to work, can anyone help to check?
def alphabet(begin, end):
for number in xrange(ord(begin), ord(end)+1):
yield chr(number)
def test(a, b):
for i in a:
for j in b:
print i, j
test(xrange(8, 10), alphabet('A', 'C'))
The result shows:
>>> 8 A
>>> 8 B
>>> 8 c
don’t know why? thanks in advance if any one can help.
Since you’ve asked for clarification, I’ll say a bit more; but really Ignacio‘s answer sums it up pretty well: you can only iterate over a generator once. The code in your example tries to iterate over it three times, once for each value in
a.To see what I mean, consider this simplistic example:
When
mygenis called, it creates an object which can be iterated over exactly once. When you try to iterate over it again, you get an empty iterable.This means you have to call
mygenanew, every time you want to iterate over it`. So in other words (using a rather verbose style)…If you wanted to bind your arguments to your generator and pass that as an argumentless function, you could do this (using a more terse style):
The
lambdajust defines an anonymous function; the above is identical to this: