Wednesday, 4 September 2013

Skipping over values in a generator function

Skipping over values in a generator function

I am writing a generator function that gives me alpha-characters, like so,
def gen_alphaLabels():
a = range(65,91)
for i in a:
yield chr(i)
k = gen_alphaLabels()
for i in range(26):
print k.next(),
This yields,
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
This works....
I would the function to skip over some characters that in a donotInclude
list. I could do this is outside the generator, like so,
k = gen_alphaLabels()
donotInclude = ['D','K','J']
for i in range(26):
r = k.next()
if r not in donotInclude:
print r,
This yields the desired result of skipping over 'D','K' and 'J'
A B C E F G H I L M N O P Q R S T U V W X Y Z
Is there a way include the logic relating to skipping over characters in
the generator function? Some thing along the lines of
def gen_alphaLabels():
a = range(65,91)
for i in a:
r = chr(i)
if r in donotInclude:
yield self.next()
else:
yield r

No comments:

Post a Comment