是否可以创建一个迭代器/生成器,它会根据上一次迭代的一些结果来决定下一个值?
即
y = None
for x in some_iterator(ll, y):
y = some_calculation_on(x)
我希望选择下一个 x 的逻辑取决于计算结果,允许不同的逻辑用于不同的结果,就像在搜索问题中一样。
我还想将如何选择下一个 x 和对 x 的计算尽可能分开。
请您参考如下方法:
你知道你可以使用 generator.send 发送到生成器吗? ?所以是的,你可以有一个发电机来根据外界的反馈改变它的行为。来自文档:
generator.send(value)Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The
send()method returns the next value yielded by the generator [...]
例子
这是一个计数器,只有在被告知这样做时才会增加。
def conditionalCounter(start=0):
while True:
should_increment = yield start
if should_increment:
start += 1
用法
由于使用 for 循环的迭代不允许使用 generator.send,因此您必须使用 while 循环。
import random
def some_calculation_on(value):
return random.choice([True, False])
g = conditionalCounter()
last_value = next(g)
while last_value < 5:
last_value = g.send(some_calculation_on(last_value))
print(last_value)
输出
0
0
1
2
3
3
4
4
5
让它在for循环中工作
您可以通过创建一个 YieldReceive 类在 for 循环中完成上述工作。
class YieldReceive:
stop_iteration = object()
def __init__(self, gen):
self.gen = gen
self.next = next(gen, self.stop_iteration)
def __iter__(self):
return self
def __next__(self):
if self.next is self.stop_iteration:
raise StopIteration
else:
return self.next
def send(self, value):
try:
self.next = self.gen.send(value)
except StopIteration:
self.next = self.stop_iteration
用法
it = YieldReceive(...)
for x in it:
# Do stuff
it.send(some_result)
