Converting a yield statement to a Generator Expression in Python
I have a question regarding converting a yield statement to a generator expression
So I have this small yield method that gets a function and a starting number as its inputs, and basically calls the function for each previous number that was called ie:
etc. Here is the code in Python:
def some_func(function, number):
while True:
yield number
number = function(number)
What are the ways of converting this snippet into a Generator Expression? I'm guessing that there is a very pythonic and elegant way of doing this, but I just can't get my head around it.
I am quite unfamiliar with Generator Expressions, hence why I'm asking for help but I do want to expand my knowledge of Gen Exp in general and of Python in particular
Stick to what you have now. You could convert the function to a generator expression but it'd be an unreadable mess.
Generator expressions need another iterable to loop over, which your generator function doesn't have. Generator expressions also don't really have access to any other variables; there is just the expression and the loop, with optional if
filters and more loops.
Here is what a generator expression would look like:
from itertools import repeat
number = [number]
gen = ((number[0], number.__setitem__(0, function(number[0]))[0] for _ in repeat(True))
where we abuse number
as a 'variable'.
上一篇: 生成器表达式与产量