Python使用反馈创建迭代器/生成器 [英] Python create an iterator/generator with feedback

查看:81
本文介绍了Python使用反馈创建迭代器/生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个迭代器/生成器,该迭代器/生成器将根据上一次迭代的某些结果来决定下一个值?

Is it possible to create a iterator/generator which will decide on the next value based on some result on the previous iteration?

y = None
for x in some_iterator(ll, y):
  y = some_calculation_on(x)

我希望选择下一个x的逻辑取决于计算结果,从而为不同的结果提供不同的逻辑,就像在搜索问题中一样.

I would like the logic of choosing the next x to depend on the calculation result allowing different logic for different results, much like in a search problem.

我也想尽可能地分开选择下一个xx上的计算.

I also want to keep the how to choose the next x and the calculation on x as separate as possible.

推荐答案

您是否可以使用

Did you that you can send to a generator using generator.send? So yes, you can have a generator to change its behaviour based on feedback from the outside world. From the doc:

generator.发送()

继续执行并将值发送"到生成器函数中. value参数成为当前yield表达式的结果. send()方法返回生成器产生的下一个值 [...]

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 [...]

示例

这里是一个计数器,只有在被告知这样做时才会增加.

Example

Here is a counter that will increment only if told to do so.

def conditionalCounter(start=0):
    while True:
        should_increment = yield start
        if should_increment:
            start += 1

用法

由于使用for循环进行的迭代不允许使用generator.send,因此必须使用while循环.

Usage

Since iteration with a for-loop does not allow to use generator.send, you have to use a while-loop.

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循环中进行.

Make it work in a for-loop

You can make the above work in a for-loop by crafting a YieldReceive class.

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)

这篇关于Python使用反馈创建迭代器/生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆