Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"yield from" another generator but after processing

How do we yield from another sub-generator, but with transformation/processing?

for example: in code below, main_gen yields x after transformation using f(x)

def f(x):
   return 2*x

def main_gen():
   for x in sub_gen():
      yield f(x)

can this be replaced with yield from and if so how?

def main_gen():
     yield from ***
like image 709
toing Avatar asked Dec 31 '22 19:12

toing


1 Answers

You could do:

def main_gen():
    yield from map(f, sub_gen())
   

But then, why not:

def main_gen():
    return map(f, sub_gen())

Which is a lazy iterator anyway.

like image 76
user2390182 Avatar answered Jan 02 '23 07:01

user2390182