I want a generator that returns what I sent to it in the following iteration:
>>>g = delayed_generator()
>>>g.send(None)
>>>g.send('this')
>>>g.send('is')
'this'
>>>g.send('delayed')
'is'
>>>g.send('!')
'delayed'
I've come up with a solution that involves three internal variables and I'm wondering if there is a simpler way of doing it. This is my solution:
def delayed_generator():
y = None
z = None
while True:
x = yield y
y=x
y = yield z
z=y
z = yield x
x=z
You can keep a queue:
def delayed_generator():
q = [None, None]
while True:
x = yield q.pop(0)
q.append(x)
g = delayed_generator()
g.send(None), g.send('this'), g.send('is'), g.send('delayed'), g.send('!')
returns
(None, None, 'this', 'is', 'delayed')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.