Skipping values ​​in a generator function

I am writing a generator function that gives me alpha characters like

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 gives,

 ABCDEFGHIJKLMNOPQRSTU VWXYZ 

It works....

I could skip some of the characters in the donotInclude list. I could do this outside the generator, for example,

 k = gen_alphaLabels() donotInclude = ['D','K','J'] for i in range(26): r = k.next() if r not in donotInclude: print r, 

This gives the desired result of skipping over 'D', 'K' and 'J'

 ABCEFGHILMNOPQRSTUVWX YZ 

Is there a way to enable logic related to skipping characters in generator functions? Something like

 def gen_alphaLabels(): a = range(65,91) for i in a: r = chr(i) if r in donotInclude: yield self.next() else: yield r 
+6
source share
4 answers

Without using continue + a slight code reduction:

 def gen_alphaLabels(donotInclude): for i in range(65,91): char = chr(i) if char not in donotInclude: yield char 
+6
source

continue to the rescue:

 def gen_alphaLabels(): a = range(65,91) for i in a: r = chr(i) if r in donotInclude: continue yield r 
+7
source

You can use string.uppercase instead of chr (I also used list comprehension instead of if ):

 import string def gen_alphalabels(exclude): labels = [c for c in string.uppercase if c not in exclude] for label in labels: yield label 

The description of the list above may be a matter of taste, but this allows us to use yield from in Python 3.3, making it even more concise:

 import string def gen_alphalabels(exclude): labels = [c for c in string.ascii_uppercase if c not in exclude] yield from labels 
0
source

In this case, you do not need to use any variables in your gene.

 def gen_alphaLabels(): for i in range(65,91): if chr(i) not in donotInclude: yield (chr(i)) 
0
source

Source: https://habr.com/ru/post/953184/


All Articles