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
182 views
in Technique[技术] by (71.8m points)

python 3.x - Proper way to list a second heirarchy generator

Let's say we have a generator that do operations on a generator, here's an example:

def print_forever(n): 
     while True:
         yield n 
  
def limit_gen(gen, n): 
     for i in range(n): 
         yield next(gen) 

What's the proper way to insert the values of the generator in a list? list(limit_gen(print_forever(2), 5) for example raises a StopIteration.


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

1 Answer

0 votes
by (71.8m points)

In your example the print_forever is instanciated once, then passed to the limit_gen one. After being called once, the first one has yield its one value and reach its own end, raising a StopIteration exception.

There are various ways to make it work, you could for example instanciate a new generator at each iteration:

def print_forever(v):
    yield v

def limit_gen(gen, v, n):
    for _ in range(n):
        yield next(gen(v))

for v in limit_gen(print_forever, 2, 5):
    print(v)

Another option is to make a really infinite generator:

def print_forever(v):
    while 1:
        yield v

def limit_gen(gen, n):
    for _ in range(n):
        yield next(gen)

for v in limit_gen(print_forever(2), 5):
    print(v)

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

...