gpt4 book ai didi

python - 从消费者生成器返回单个值

转载 作者:行者123 更新时间:2023-12-01 05:51:55 24 4
gpt4 key购买 nike

我有一个消费者生成器的管道。我想从最后一个消费者中在某个时间点返回结果。这有效:

class StopIterationWithResult(StopIteration):
def __init__(self, result):
super(StopIterationWithResult, self).__init__()
self.result = result

# for definition fo consumer decorator see http://www.python.org/dev/peps/pep-0342/
@consumer
def waitfor3():
while True:
value = (yield)
if value == 3:
raise StopIterationWithResult('Hello')

c = waitfor3()
for i in range(10):
try:
print 'calling', i
c.send(i)
except StopIterationWithResult as r:
print 'stopped', r.result
break

还有更好的办法吗?例如,如果生成器由于 return 语句而引发 StopIteration,您能否访问生成器的返回值?

根据@alexis的要求,下面是一个带有管道的示例:

class StopIterationWithResult(StopIteration):
def __init__(self, result):
super(StopIterationWithResult, self).__init__()
self.result = result

@consumer
def add1_filter(consumer):
while True:
value = (yield)
consumer.send(value+1)

@consumer
def waitfor3():
while True:
value = (yield)
print 'got', value
if value == 3:
raise StopIterationWithResult('Hello')

c = waitfor3()
f = add1_filter(c)
for i in range(10):
try:
print 'calling', i
f.send(i)
except StopIterationWithResult as r:
print 'stopped', r.result
break

这与 @Martijn Pieters 的答案相同 - 但使过滤器变得更难看:

@consumer
def add1_filter(consumer):
result = None
while True:
value = (yield result)
result = consumer.send(value+1)

@consumer
def waitfor3():
while True:
value = (yield)
print 'got', value
if value == 3:
yield 'Hello'
break

c = waitfor3()
f = add1_filter(c)
r = None
for i in range(10):
try:
print 'calling', i
r = f.send(i)
except StopIteration:
print 'stopped', r
break

最佳答案

产量是双向的。在右侧表达式中使用时,它将接收并用作语句,它会生成表达式的结果。

只需产生结果值:

def waitfor3():
while True:
value = (yield)
if value == 3:
yield 'Hello'
break

c = waitfor3()
for i in range(10):
try:
print 'calling', i
result = c.send(i)
except StopIteration:
print 'stopped', result
break

关于python - 从消费者生成器返回单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13942413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com